M87星云

导航

02、spring Aop入门配置

AOP概念: spring aop为面向切面编程,通过编译方式和运行期动态代理实现程序应用功能的一种技术;其目的是为降低程序部件间的耦合度,提高可复用性。

1、导入依赖

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

2、创建连接点服务层业务

服务接口:
public interface Myservice {
public abstract void save();
}

服务实现类
public class MyserviceImpl implements Myservice {
@Override
public void save() {
System.out.println("保存业务....");
}
}

3、创建增强类
public class Logger {

public void befoerLog(){
System.out.println("前置通知....");
}

public void afterReturningLog(){
System.out.println("后置通知....");
}

public void afterThrowing(){
System.out.println("异常通知....");
}

public void afterLog(){
System.out.println("最终通知....");
}

}

4、配置bean.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">

<!--配置MyserviceImpl对象-->
<bean id="myservice" class="com.boat.service.impl.MyserviceImpl"></bean>

<!--配置Logger对象-->
<bean id="logger" class="com.boat.advice.Logger"></bean>

<!--配置通知-->
<aop:config>

<!--配置切入点,及表达式-->
<aop:pointcut id="mypointcut" expression="execution(* com.boat.service..*.*(..))"/>

<!--建立增强类与切面点关系-->
<aop:aspect id="advisor" ref="logger">
<!--配置前置通知-->
<aop:before method="befoerLog" pointcut-ref="mypointcut"></aop:before>
<!--配置后置通知-->
<aop:after-returning method="afterReturningLog" pointcut-ref="mypointcut"></aop:after-returning>
<!--配置异常通知-->
<aop:after-throwing method="afterThrowing" pointcut-ref="mypointcut"></aop:after-throwing>
<!--配置最终通知-->
<aop:after method="afterLog" pointcut-ref="mypointcut"></aop:after>
</aop:aspect>
</aop:config>
</beans>

5、编写测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:service.xml"})
public class TestSpring {

@Autowired
private Myservice myservice;

@Test
public void show(){
myservice.save();
}

}

运行结果为:

 

 




posted on 2021-05-25 17:07  挽留匆匆的美丽  阅读(70)  评论(0编辑  收藏  举报