AOP:面向切面编程
功能:在不改变原有代码的基础之上,通过Spring为原有代码做功能增强。降低业务逻辑耦合度,提高程序可用性。
配置流程:
(1)添加Maven依赖
(2)写需要添加增强功能的业务代码
(3)写增强类
(4)调整配置文件app.xml
(5)使用
具体过程:
(1)依赖(AOP+aspectj)
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
(2)业务代码
public class UserController {
public void fun(){
System.out.println("公司的原古代码……");
}
}
(3)增强类
//放置所有的增强功能
@Component
@Aspect
public class BDAdvice {
@Before("execution(public void com.zparkep.controller.UserController.fun())")
public void before(){
System.out.println("before advice");
}
}
(4)调整配置文件spring.xml
?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">
<context:component-scan base-package="com.zparkep"/>
<aop:aspectj-autoproxy/>
</beans>
(5)使用
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:app.xml")
public class AdviceTest {
//对UserController进行增强测试
@Autowired
private UserController userController;
@Test
public void fun(){
userController.fun();
}
}
结果:
成功
注:@Before("execution(public void com.zparkep.controller.UserController.fun())")表示对public类型的返回值为void的 com.zparkep.controller包下的UserController类下的fun方法做前置增强。
设对public类型的返回值为String的 com.zparkep.controller包下的所有类下的所有方法【参数不确定】做前置增强,则注解为@Before("execution(public String com.zparkep.controller.*.*(..))")
若多个增强方法对具有同一规则的方法做增强,根据DRY原则,需要提取规则,可使用@Pointcut()注解,举例。
为UserController类下的所有方法添加前置增强和后置增强:
@Aspect
@Component
@Log
public class BDadvice {
@Pointcut("execution(public void com.zparkep.controller.UserController.*())")
public void fun(){
}
@After("fun())")
public void after(){
log.info("after advice");
}
@Before("fun()")
public void before(){
System.out.println("before advice");
}
}