1.引入jar包
sprig框架基础包+JUntil整合包+日志包+AOP包
spring的传统AOP的开发的包
spring-aop-4.2.4.RELEASE.jar
com.springsource.org.aopalliance-1.0.0.jar
aspectJ的开发包
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aspects-4.2.4.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" 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>
3.创建实现类
public interface UserService { public void save(); public void update(); public void delete(); }
@Service(value="userService") public class UserServiceImpl implements UserService { @Override public void save() { // TODO Auto-generated method stub System.out.println("业务层:保存客户.."); } @Override public void update() { // TODO Auto-generated method stub System.out.println("业务层:更新客户.."); } @Override public void delete() { // TODO Auto-generated method stub System.out.println("业务层:删除客户.."); } }
4.将实现类托管于Spring注解方式
5.创建切面类
public class MyAspectAnn { public void log(){ System.out.println("前置通知.."); } public void arround(ProceedingJoinPoint joinPoint){ System.out.println("环绕通知1.."); System.out.println("环绕通知2.."); } public void after(){ System.out.println("后置通知.."); } }
6.将切面类托管于Spring
7.定义切面类方法的切入点
8.在配置文件中开启自动代理,并扫描注解
<!-- 扫描注解 --> <context:component-scan base-package="com.spring.demo1"/> <!-- 开启自动代理 --> <aop:aspectj-autoproxy/>
9.编写测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class Demo1 { @Resource(name="userService") private UserService userService; @Test public void m01(){ System.out.println("======================="); userService.save(); System.out.println("======================="); userService.update(); System.out.println("======================="); userService.delete(); System.out.println("======================="); } }
效果:
时间: 2024-10-07 01:54:55