M87星云

导航

03、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();
}

服务实现类
@Service
public class MyServiceImpl implements MyService {

@Override
public void save() {
System.out.println("保存业务");
}

}

3、创建增强类
@Component("logger")
@Aspect
public class Logger {

@Pointcut("execution(* com.boat.service..*.*(..))")
private void pintcut(){ }

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

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

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

@After("pintcut()")
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">

<!--启用注解扫描器配置-->
<context:component-scan base-package="com.boat"></context:component-scan>

<!--启用aop注解自动配置-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

5、编写测试类

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

@Autowired()
private MyService myService;

@Test
public void sho(){
myService.save();
}

}
运行结果为:

 





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