我的Aspect课程将是,
@Configuration
@EnableAspectJAutoProxy
@Component
@Aspect
public class AspectClass {
@Before("execution(* com.pointel.aop.test1.AopTest.beforeAspect())")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before running the beforeAspect() in the AopTest.java class!");
System.out.println("Hijacked Method name : " + joinPoint.getSignature().getName());
System.out.println("************************");
}
}
我的其他java类
public class AopTest {
public void beforeAspect() {
System.out.println("This is beforeAspect() !");
}
}
我的主要课程是
public class MainMethod {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("ApplicationContext/applicationContext.xml");
AopTest test = (AopTest)context.getBean("bean1");
test.beforeAspect();
}
}
我的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: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="bean1" class="com.pointel.aop.test1.AopTest" />
</beans>
在此,当运行Main方法时,AspectClass中的@Before(“execution(* com.pointel.aop.test1.AopTest.beforeAspect())”)将不会在AopTest中的beforeAspect()之前执行.
肯定赞赏好的答案.
解决方法:
首先,如果您要使用基于注释的配置,请使用AnnotationConfigApplicationContext而不是FileSystemXmlApplicationContext.并删除applicationContext.xml文件,只需在配置类中添加@Bean方法即可.像这样的东西:
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "your.aspect.package")
public class AspectConfig {
@Bean
public AopTest aopTest() {
return new AopTest();
}
}
在你的主要
public class MainMethod {
public static void main(String[] args) {
AnnotationConfigApplicationContextcontext = new AnnotationConfigApplicationContext(AspectConfig.class);
// don't forget to refresh
context.refresh();
AopTest test = (AopTest)context.getBean("aopTest");
test.beforeAspect();
}
}
在AspectClass中,你应该有@ Component,@ Aspect,你的方法应该有像@Before这样的建议或切入点注释.它需要是@Component,以便Spring知道扫描它.