Spring的Aop学习:首先需要到Spring的需要的jar:!
[注意需要导入commons-logging的jar不然spring测试会出现错误]
在学习的Aop的时候需要到图片中的框住的jar的!
实现Aop的方法之一:实现接口编写Aspect(切面实现前置通知方法implements MethodBeforeAdvice)
public class Log implements MethodBeforeAdvice{
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {System.out.println(target.getClass().getName()+"的"+method.getName()); } }`
编写接口和实现类;
在Spring的IOC容器里配置切面和目标类/
<!-- target目标类(代理的类) -->
<beanid="userService"class="cn.xst.service.UserServiceImpl"></bean>
<!-- 前置切面 -->
<beanid="log"class="cn.xst.log.Log"></bean>
<!-- 把切面和目标类 -->
<aop:config><!-- 切入点 -->
<aop:pointcut expression="execution(* cn.xst.service.impl.*.*(..))" id="pointcut"/>
<!-- 把切面和切入点织入 -->
<aop:advisoradvice-ref="log"pointcut-ref="pointcut"/></aop:config>
编写测试类:```
ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
UserService userService=app.getBean(UserService.class);
userService.add();输出的结果:cn.xst.service.UserServiceImpl的add增加用户
配置后置通知且切面:
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+method.getName());
}
在bean中配置切面:
<!-- 后置切面 -->
<beanid="afterlog"class="cn.xst.log.AfterLog"></bean>
在<aop:config></aop:config><!-- 把切面和切入点织入 -->
<aop:advisoradvice-ref="afterlog"pointcut-ref="pointcut"/>
修改织入的advice-ref进行测试得到结果:修改用户cn.xst.service.impl.UserServiceImpl的update
第二种实现Aop切面的编程:(自定义)
public class Log {
public void before(){
System.out.println("-----方法执行前--------");
}
public void after(){
System.out.println("-----方法执行后--------");
}}
需要在Spring的IOC容器中配置:
<!-- target目标类(代理的类) -->
<beanid="userService"class="cn.xst.service.impl.UserServiceImpl"></bean>
<!-- 前置切面 -->
<beanid="log"class="cn.xst.log.Log"></bean>
<!-- 把切面和目标类 -->
<aop:config>
<aop:aspectref="log">
<aop:pointcut expression="execution(* cn.xst.service.impl.*.*(..))" id="pointcut"/>
<aop:beforemethod="before"pointcut-ref="pointcut"/>
<aop:aftermethod="after"pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>