注解实现AOP代码流程变得极为简单,但是我们要明白其中的原理是何.
在我们自定义实现的AOP中加入几个注解就可以实现
注意点:
要写切面的注解-->Aspect
切入点可以直接写在增强上加上对应的注解就可以了.
配置文件中加入识别注解自动代理的代码.---->[<aop:aspectj-autoproxy/>]
目标对象不变userService和userServiceImpl
package org.west.anno; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; //切面注解 @Aspect public class Anno { // 切入点可以直接写在增强上面 @Before("execution(* org.west.service.UserServiceImpl.*(..))") public void before() { System.out.println("------>方法执行前"); } @After("execution(* org.west.service.UserServiceImpl.*(..))") public void after() { System.out.println("------>方法执行后"); } }
注意注解before 和after的包要导对,是Aspectj的包.
Spring的核心配置文件
<?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对象--> <bean id="userService" class="org.west.service.UserServiceImpl"/> <!--注解实现AOP的类--> <bean id="anno" class="org.west.anno.Anno"/> <!--识别注解自动代理--> <aop:aspectj-autoproxy/> </beans>
测试类:
public class TestDemo { @Test public void test() { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml"); UserService userService = (UserService) context.getBean("userService"); userService.add(); }
AOP小结:
-
-
需要到一个包,用来进行aop织入的包: aspectjweaver
-
注意别遗漏了切面;
-
三种实现AOP的方法
-
使用SpringAPI来实现AOP
-
使用自定义类来实现AOP
-
使用注解实现AOP
-