配置@aspectj-autoproxy切面,生成代理对象

2022-06-27 09:38:46

有时候在调用一个方法时,可能需要在调用该方法之前需要做点其他的操作,比如我要做一个往数据库中插入数据的操作,这个插入的方法有一个json数据,但是我可能在插入之前还需要往这个json参数中塞入其他的数据。这个时候spring的aspectj-autoproxy就起到了作用了。

首先可以先在配置文件中配置一个aop,如下:

<aop:aspectj-autoproxy proxy-target-class="true" >
<aop:include name="
studentInsertAspect"/>
</aop:aspectj-autoproxy>

proxy-target-class属性默认值为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy  poxy-target-class="true"/>时,表示使用CGLib

动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

<aop:include name="studentInsertAspect" />,这个地方的name为添加了@Aspect注解类名,如:

@Aspect
@Component("studentInsertAspect")
public class StudentInsertAspect{
	@Autowired
	private StudentService studentService;

	/**
	*
	**/
	@Before("execution(* com.class.service.StudentService.insert(..))")
	public void inputTestData(JoinPoint point){
  		JSONObject json = null;
        	for(Object obj : point.getArgs()){
        		if(obj instanceof JSONObject){
        			json = (JSONObject)obj;
        		}
        	}
       		if(json != null){
           		json.accumulate("studentNum","class001");
      		}
   	}
}


上面那个类用了@Before注解,是在触发了studentService的插入方法的时候,率先触发inputTestData这个方法,其中,插入的方法可能带有一个json的参数,

,然后在inputTestData方法中往json中插入一个studentNum,这样,在insert中就可以得到一个studentNum的数据。

当然还有其他的注解,有before也有after,具体的还需后续继续了解学习了,spring的功能真的是很强大,希望能多多学习!

  • 作者:yasashii
  • 原文链接:https://blog.csdn.net/yasashii/article/details/78616173
    更新时间:2022-06-27 09:38:46