Spring中全自动AOP使用
作用:多用于事务配置 和日志记录
1、导包:com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
2、全自动AOP配置
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- bean definitions here -->
<!--开启注解-->
<context:annotation-config/>
<!--注解的位置-->
<context:component-scan base-package="com.hwt"></context:component-scan>
<aop:config proxy-target-class="true">
<!--切入点--><!--注意:第一个*后与包名之间有空格,缺少会报错-->
<aop:pointcut id="myPointcut" expression="execution(* com.hwt.service.*.*(..))"/>
<!--通知-->
<aop:advisor advice-ref="myAspect" pointcut-ref="myPointcut"/>
</aop:config>
</beans>
3、原业务类:
package com.hwt.service;
import org.springframework.stereotype.Service;
@Service("studentService")
public class StudentService {
public void delete(){
System.out.println("删除学生!");
}
public void add(){
System.out.println("添加学生!");
}
public void update(){
System.out.println("修改信息!");
}
}
4、切面类:(增强类)
PS:跳坑,此处注意,导错包会出错
package com.hwt.service;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.stereotype.Component;
/**
* 切面类:增强代码与切入点的结合
*/
@Component("myAspect")
public class MyAspect implements MethodInterceptor {
public void before(){
System.out.println("开启事务。。。");
}
public void after(){
System.out.println("关闭事务。。。");
}
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
before();
//放行方法
//Object invoke = method.invoke(studentService);
Object invoke = methodInvocation.proceed();
System.out.println("拦截。。。。");
after();
return invoke;
}
}
5、测试类:
package com.hwt.test;
import com.hwt.service.StudentService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test04 {
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans04.xml");
StudentService studentService = (StudentService) context.getBean("studentService");
studentService.add();
studentService.delete();
studentService.update();
}
}
测试结果: