1.未正确定义注解:
注解定义把握两个原则
1.作用范围 @Target(ElementType.METHOD)
注解作用范围(方法上)
2.保留策略 @Retention(RetentionPolicy.RUNTIME)
保留策略(源代码、编译时和运行保留)
2.结合项目中自定义注解失效(比如日志注解)
自定义注解需要利用aop实现,通过代理对象进行调用(不能使用this调用)自定义注解标注的方法如果被本类调用,活动不到代理对象,自己注解失效。解决方法通过AopContext获取当前类的代理对象,调用该方法可解决注解失效问题。
@Service
public class HelloServiceImpl implements HelloService {
@Log
public void hello() {
System.out.println("hello方法·····");
hello1();
}
@Log
public void hello1() {
System.out.println("hello1方法·····");
}
}
上面代码执行结果:只有hello方法进行日志记录,hello1方法没有被代理对象调用,注解失效。
解决方案:
@Service
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class HelloServiceImpl implements HelloService {
@Log
public void hello() {
System.out.println("hello方法·····");
((HelloServiceImpl)AopContext.currentProxy()).hello1();
}
@Log
public void hello1() {
System.out.println("hello1方法·····");
}
}
1.加入注解:@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) 2.使用代理调用 ((HelloServiceImpl)AopContext.currentProxy()).hello1();
执行结果:
不生效相关博客 www.ucloud.cn/yun/69019.h…