I start learn AOP with spring framework 3.1.2. But I have trouble. In Beans.xml context file i wrote:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<bean id = "audience" class="com.MySpring.Audience"></bean>
<aop:config>
<aop:aspect ref="audience">
<aop:pointcut id="performance" expression="execution(* com.MySpring.Performer.perform(..))"/>
<aop:before pointcut-ref="performance" method="seatDown"/>
<aop:before pointcut-ref="performance" method="turnOffPhone"/>
<aop:after-returning pointcut-ref="performance" method="applauz"/>
<aop:after-throwing pointcut-ref="performance" method="demandRefund"/>
</aop:aspect>
</aop:config>
</beans>
And Java class
public class AOPTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext(
"Beans.xml");
}
}
// ///
class Audience {
public void seatDown() {
out.println("Seat down");
}
public void turnOffPhone() {
out.println("Turn Off Phone");
}
public void applauz() {
out.println("Aplauz");
}
public void demandRefund() {
out.println("We have money back");
}
}
////
interface Performer{
void perform();
}
But in error console i see:
Description Resource Path Location Type
Error occured processing XML 'class path resource [org/aopalliance/aop/Advice.class] cannot be opened because it does not exist'. See Error Log for more details Beans.xml /AnnotationsWiring/src line 11 Spring Beans Problem
And second error:
Description Resource Path Location Type
Error occured processing XML 'org/springframework/aop/aspectj/AspectJMethodBeforeAdvice'. See Error Log for more details Beans.xml /AOP/src line 12 Spring Beans Problem
I guess you are learning spring using examples from spring in action. In fact, you are missing a com.springsource.org.apoalliance.jar file, which is not included in org.springframework.aop.jar(though i don't know why).
Please download it at: http://sourceforge.net/projects/aopalliance/files/aopalliance/
You have the Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice because you don't include the jar into your classpath.
Related
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException: I/O
failure during classpath scanning; nested exception is
org.springframework.core.NestedIOException: ASM ClassReader failed to
parse class file - probably due to a new Java class file version that
isn't supported yet: class path resource
[springanotaciones/ComercialExp.class]; nested exception is
java.lang.IllegalArgumentException: Unsupported class file major
version 60
package springanotaciones;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class play {
public static void main(String[] args) {
ClassPathXmlApplicationContext contexto = new
ClassPathXmlApplicationContext("applicationContext.xml");
Empleado pipi = contexto.getBean("comercial", Empleado.class);
System.out.println(pipi.setInforme());
}
}
package springanotaciones;
public interface Empleado {
public String setTarea();
public String setInforme();
}
package springanotaciones;
import org.springframework.stereotype.Component;
#Component("comercial")
public class ComercialExp implements Empleado {
#Override
public String setTarea() {
return"vender y vernder";
}
#Override
public String setInforme() {
return"El comercial genero un informe";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
">
<context:component-scan base-package="springanotaciones"></context:component-scan>
</beans>
Right,the problem was the JDK16ยก
finally I change de JDK 16 for the JDK 14 for this project and is working, maybe this help someone in the future.
Sorry for my inglish.
I've got a question for programmatically added properties to a spring context.
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ConfigurableEnvironment ctxEnvironment = ctx.getEnvironment();
ctxEnvironment.getPropertySources().addFirst(new ResourcePropertySource("rootProperties", new FileSystemResource("/tmp/root.properties")));
ctx.load(new ClassPathResource("/context/application-context.xml"));
ctx.refresh();
root.properties:
test=hello
Snippet from application context:
...
<property name="test" value="${test} world"/>
...
When I load the bean from the context, ${test} is not substituted with "hello".
Spring version: 5.1.5.RELEASE
What am I missing here?
PS: Btw, this works:
System.out.println("Text: " + ctxEnvironment.resolvePlaceholders("${test}"));
Output:
Text: hello
EDIT: Sorry, I forgot to add: I don't want to use the context:property-placeholder bean, because I know the location of the properties file only at runtime.
I reproduced your case and it's working for me. You need to add a property place holder in your applicationContext.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="file:/tmp/root.properties" />
<bean id="myA" class="com.zpavel.MyA">
<property name="test" value="${test}" />
</bean>
</beans>
For example a simple bean :
public class MyA {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
You can load it with :
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/context/application-context.xml");
MyA myA = context.getBean(MyA.class);
System.out.println(myA.getTest());
It will print "hello" as expected.
Your code is working fine.
I have tested with this.
applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder
location="application.properties" />
<bean id="demo"
class="com.example.Demo">
<property name="value1" value="${test} world" />
</bean>
</beans>
application.properties :
test = Hello
Demo.java :
public class Demo {
String value1;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
#Override
public String toString() {
return value1;
}
}
Test.java :
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Demo demo = (Demo) classPathXmlApplicationContext.getBean("demo");
System.out.println(demo);
classPathXmlApplicationContext.close();
}
}
When you run, the output :
Hello world
The problem is with the bean. Please check it.
After some more diving into the spring API I found a pure programmatic solution to my problem without the need of a context:property element. For anyone interested, here is the full source:
Test.java
public class Test {
public static void main(String[] args) throws Exception {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new ResourcePropertySource("rootProperties", new ClassPathResource("/root.properties")));
configurer.setPropertySources(propertySources);
ctx.addBeanFactoryPostProcessor(configurer);
ctx.load(new ClassPathResource("/ctx.xml"));
ctx.refresh();
TestBean bean = ctx.getBean(TestBean.class);
System.out.println(bean.getString());
}
}
TestBean.java
public class TestBean {
String string = "";
public String getString() { return string; }
public void setString(String string) { this.string = string; }
}
ctx.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans classpath:/org/springframework/beans/factory/xml/spring-beans.xsd">
<beans>
<bean class="TestBean">
<property name="string" value="${test} world"/>
</bean>
</beans>
</beans>
root.properties
test=hello
I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application
My process class:
#Configurable("checkLicense")
public class CheckLicense {
String licensePath ;
#Value("${licenseKeyNotFound}")
String licenseKeyNotFound;
public boolean checkIn(String licensepath) {
System.out.println("hello "+licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
My ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class="com.smart.applicationlicense.CheckLicense"
scope="prototype">
</bean>
</beans>
Here is my properties file.
licenseKeyNotFound = License File Corrupted
Here is my servlet xml.
<context:property-placeholder location="conf/LicenseSettings.properties"
order="2" ignore-unresolvable="true" />
Eventhough I have used the #Configurable annotation along with the attributes Autowire.BY_NAME, Autowire.BY_TYPE, I am unable to initiate the variable of licenseKeyNotFound from the property file.
I was able to initiate the variable from a controller but not from this class which is declared #Configurable.
Can anyone please let me know what I am missing or what's wrong with my code?
Please let me know if there is something required from my code.
try this:
in your spring xml:
<context:property-placeholder location="classpath:your.properties" />
<context:load-time-weaver />
Try this
#Configurable
public class CheckLicense {
String licensePath;
String licenseKeyNotFound;
#Value("${licenseKeyNotFound}")
public void setLicenseKeyNotFound(String licenseKeyNotFound) {
this.licenseKeyNotFound = licenseKeyNotFound;
}
public boolean checkIn(String licensepath) {
System.out.println("hello " + licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
in your properties file
licenseKeyNotFound=${value}
I 've designed a db application, but need to handle the exception connecting to db using spring aop, classes i 've are shown below
LoginInterface.java
LoginInterface(){
ApplicationContext context = new ClassPathXmlApplicationContext("LoginApp.xml");
Login login = (Login) context.getBean("Login");
login.loginMethod(username,password);
}
Login.java
{
loginMethod(String username, char[] pwd) throws ClassNOtFoundException, SQLException{
...
}
}
LoginProfiler.java
package dbapp;
import java.sql.SQLException;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.JoinPoint;
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#Around("loginMethod()")
public void handleException(final ProceedingJoinPoint pJoinPoint )throws Throwable{
try{
pJoinPoint.proceed();
}catch(Exception e) {
if((e.getCause().toString()).contains("UnknownHostException") ){
System.out.println("Unknown Host ");
}else if((e.getCause().toString()).contains("ConnectException")){
System.out.println("Connection Problem ");
}
}
}
}
LoginApp.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-destroy-method="destroy"
default-init-method="afterPropertiesSet"
default-autowire="byName">
<!-- Enable the #AspectJ support -->
<aop:aspectj-autoproxy />
<bean id="LoginProfiler" class="dbapp.LoginProfiler" />
<bean id="Login" class="dbapp.Login" />
</beans>
I've got the following Exception
Erg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Login' defined in class path resource [LoginApp.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at
..
Caused by: java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut LoginMethod
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:315)
at org.springframework.aop.aspectj.AspectJExpressionPointcut.buildPointcutExpression(AspectJExpressionPointcut.java:206)
at
Try this.
#Aspect
public class LoginProfiler {
#Pointcut("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void loginMethod(){}
#AfterThrowing("loginMethod()")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
or
#Aspect
public class LoginProfiler {
#AfterThrowing("execution(* dbapp.Login.loginMethod(String, char[])throws java.lang.ClassNotFoundException, java.sql.SQLException)")
public void handleException(final JoinPoint joinPoint){
System.out.println("Am able to Handle");
}
}
Also it would be better if you spend some time learning about spring-aop. From your question it looks like you really don't understand AOP. You are trying to cut and paste from some sample code.