参考自黑马培训机构
创建项目,引入jar包
编写目标类,切面类并完成配置
package spring.day2_aop2; /* * 编写目标类 */ public class OrderDao { public void save() { System.out.println("orderDao的save方法已经执行......"); } public void delete() { System.out.println("orderDao的delete方法已经执行......"); } public void update() { System.out.println("orderDao的update方法已经执行......"); } public void find() { System.out.println("orderDao的find方法已经执行......"); } }
package spring.day2_aop2; /* * 编写切面类 */ public class MyAspect { public void checkPri() { System.out.println("=============权限校验(前置通知)============="); } }
<?xml version="1.0" encoding="UTF-8"?> <!-- ===============================引入aop开发的约束============================ --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- ====在注解文件里开启aop的开发===== --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- 配置目标类 --> <bean id="orderDao" class="spring.day2_aop2.OrderDao"></bean> <!-- 配置切面类 --> <bean id="myAspect" class="spring.day2_aop2.MyAspect"></bean> </beans>
在配置文件中开启aop的注解开发
使用注解对目标类进行增强
package spring.day2_aop2; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; /* * 编写切面类 */ @Aspect public class MyAspect { @Before(value="execution(* spring.day2_aop2.OrderDao.save(..))") public void checkPri() { System.out.println("=============权限校验(前置通知)============="); } }
编写测试类并完成测试
package spring.day2_aop2; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /* * 编写测试类 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext5.xml") public class SpringDemo1 { @Resource(name="orderDao") private OrderDao orderDao; @Test public void demo1() { orderDao.save(); orderDao.delete(); orderDao.update(); orderDao.find(); } }