注解方式开发aop:
从哪入手:
从XML入手,加入DI解析器和IOC注解解析器
@Component---贴在类上面的注解:主要的功能是把这个类的对象注入到Spring IOC容器中
@Autowired---贴在想要获取的对象,主要的功能是Sping IOC容器中获取想要的对象
那么问题来了,AOP怎么配置呢?
首先在增强方法类上配置一个@@Aspect--切面(相当于一个增强的方法)
然后在方法里面加入一个 @Aspect 注解
@Component //<bean id="transcations" class="Transcations.Source_Transcation"/>
@Aspect //1.<aop:aspect ref="transcations" >
public class Source_Transcation {
//2.<aop:pointcut id="TX_Area" expression="execution(* Spring_StaticPoxy_Service.*Service.*(..))"/>
@Pointcut("execution(* Spring_StaticPoxy_Service.*Service.*(..))")
public void TX_Area() {//id="TX_Area",上面的ID和方法名一致之后,AOP的配置和这个方法的功能也就一致了。
^
} |
|
|
@Before("TX_Area()")// 3.在需要的方法上贴上对应的注解和对哪些方法做增强的方法名,
public void openSource(JoinPoint joinpoint) {
System.out.println("--------代理对象---------"+joinpoint.getThis().getClass());
System.out.println("--------真实目标对象---------"+joinpoint.getTarget().getClass());
System.out.println("--------被增强方法的参数---------"+Arrays.toString(joinpoint.getArgs()));
System.out.println("---------连接点的签名--------"+joinpoint.getSignature());
System.out.println("--------当前连接点的类型---------"+joinpoint.getKind());
System.out.println("--------开启事物---------");
}
在使用注解的时候,需要注意⚠️:1,注解本身,2.被贴的程序,3.第三方赋予注解相应的功能
现在 我们在配置AOP的注解的时候 缺少了第三步骤,
<!-- AOP的注解解析器 -->
<aop:aspectj-autoproxy/>
如果显示报错:but was actually of type 'com.sun.proxy.$Proxy24'
说明jdk的动态代理和CGLIB的动态代理冲突,
怎么办呢?
在AOP注解中添加 一个设置:
<!-- false:class com.sun.proxy.$Proxy25- JDK 的动态代理 -->
<!-- true: EmployeeServiceIMPL$$EnhancerBySpringCGLIB$$6e5536f5 CJLIB的动态代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>使用CJLIB的动态代理
默认是false,使用的是JDK的动态代理
还有一个小细节要注意:就是当没有接口的时候使用CGLIB的时候,在AOP中的增强对象中的语句指向的是接口改成指向类,还有就是在Spring连接池中获取类的bean对象 而不是接口的bean对象。
@Pointcut("execution(* Spring_StaticPoxy_Service.*Service.*(..))")---对应的是接口
@Pointcut("execution(* Spring_StaticPoxy_Service.*ServiceIMPL.*(..))")--对应的是类
还有就是获取的bean对象的时候
@Autowired
public IEmployeeService service;--接口的bean对象
@Autowired
public EmployeeServiceIMPL service;--没有接口的bean对象
Spring是非常的智能,当我们有接口的时候 通过配置既可以使用CGLIB的动态代理 也可以使用JDK的动态代理
没有接口的时候 使用CGLIB的动态代理
源码百度云盘自取:链接:https://pan.baidu.com/s/15-r83NPYylzqkjGBl6urwg 密码:2682