场景
去饭店吃饭的时候,在进入饭店时门卫会为你开门,并问候说“欢迎光临”,当你吃完离开时,门卫会说“请慢走,欢迎下次光临”。此场景下涉及如下两个角色:
顾客(customer):目标对象,来吃饭(eat)
门卫(doorkeeper):切面对象,欢迎和欢送(welcome、leave)
编写程序
1、引入依赖
<!-- Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<!-- Aop依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2、编写目标对象和切面
顾客
@Component
public class Customer {
public void eat(){
System.out.println("顾客:在饭店吃饭......");
}
}
门卫
@Component
public class Doorkeeper {
public void welcome(){
System.out.println("门卫:欢迎光临......");
}
public void leave(){
System.out.println("门卫:请慢走,欢迎下次光临!!!");
}
}
3、注入ioc,并配置织入
<?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: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">
<!-- 目标对象 -->
<bean id="customer" class="com.shine.aop.Customer"></bean>
<!-- 切面对象 -->
<bean id="doorkeeper" class="com.shine.aop.Doorkeeper"></bean>
<!-- 配置织入:告诉Spring框架,哪些方法(切点)要进行哪些增强(前置、后置.......)-->
<aop:config>
<!-- 声明切面 -->
<aop:aspect ref="doorkeeper" >
<!-- 切面:切点+通知-->
<aop:before method="welcome" pointcut="execution(public void com.shine.aop.Customer.eat())"></aop:before>
<aop:after method="leave" pointcut="execution(public void com.shine.aop.Customer.eat())"></aop:after>
</aop:aspect>
</aop:config>
</beans>
测试
1、引入依赖
<!-- Spring测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.3</version>
</dependency>
<!-- junit单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2、编写测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
Customer customer;
@Test
public void test(){
customer.eat();
}
}