Spring的AOP的基于AspectJ注解开发
程序员文章站
2022-07-12 23:07:46
...
1 配置文件的头
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
2 编写目标类并配置
public class OrderDao {
public void save() {
System.out.println("执行了save方法");
}
public void update() {
System.out.println("执行了update方法");
}
public void find() {
System.out.println("执行了find方法");
}
public void delete() {
System.out.println("执行了delete方法");
}
}
<bean id="orderDao" class="com.xu.spring.demo1.OrderDao"></bean>
3 编写切面类,配置
/*
* 注解的切面类
*/
public class MyAspectAnno {
public void before(){
System.out.println("前置增强");
}
}
<bean id="myAspect" class="com.xu.spring.demo1.MyAspectAnno"></bean>
4 使用注解的AOP对目标类进行增强
其实就是在前一个标题里面写的切面类上进行配置
/*
* 注解的切面类
*/
@Aspect
public class MyAspectAnno {
@Before(value="execution(* com.xu.spring.demo1.OrderDao.save(..))")
public void before(){
System.out.println("前置增强");
}
}
5 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDemo1 {
@Resource(name="orderDao")
private OrderDao orderDao ;
@Test
public void Demo1(){
orderDao.save();
orderDao.find();
orderDao.delete();
orderDao.update();
}
}
6 Spring的注解的AOP的通知类型
-
Spring的注解的AOP的通知类型
-
@Before:前置通知
-
@AfterReturning:后置通知
-
@Around:环绕通知
-
@AfterThrowing:异常抛出通知
-
@After:最终通知
-
@Pointcut:切入点的注解
-
上一篇: springMVC基于注解开发