本次用纯注解的形式配置AOP切面。
我们需要两个Jar包(注意是1.7版本)
- aspectjweaver-1.7.4.jar
- aspectjrt-1.7.4.jar
首先查看一下项目结构
下面是Service接口与实现类
public interface Service {
/**
* 添加方法
*/
public void add ();
}
public class ServiceImpl implements Service{
/**
* 添加方法
*/
@Override
public void add (){
System.out.println("Service调用add()方法,插入数据库数据。");
}
}
Aop类
/**
* 基于注解配置的切面
* @author dou
*
*/
@Aspect
@Component
public class Aop1{
/**
* 定义一个切点
*/
@Pointcut("execution(* com.service..*.*(..))")
public void cut(){};
@Before("cut()")
//@Before("execution(* com.service..*.*(..))")
public void before() {
System.out.println("开启事务。");
}
@After("cut()")
//@After("execution(* com.service..*.*(..))")
public void after() {
System.out.println("结束事务。");
}
@AfterThrowing("cut()")
//@AfterThrowing("execution(* com.service..*.*(..))")
public void AfterReturning() {
System.out.println("抛出异常,事务回滚。");
}
}
XML配置
<!-- 自动扫包 -->
<context:component-scan base-package="com.*"/>
<!--
声明自动为spring容器中那些配置
@aspectJ切面的bean创建代理,织入切面。
-->
<aop:aspectj-autoproxy/>
Test测试类
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
Service service = (Service) context.getBean("serviceDemo");
service.add();
}