aop的使用步骤
-
添加依赖
<!--spring的依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.16</version> </dependency> <!--aspectj的依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.16</version> </dependency>
-
创建目标类:接口和实现类
aop要做的就是是给类中的方法增加功能
-
目标类示例:
package com.cfl.service.impl; import com.cfl.service.SomeService; public class SomeServiceImpl implements SomeService { @Override public void dosome(String name, Integer age) { System.out.println("执行力someservice()的dosome()方法"); } }
-
-
创建切面类:普通类
-
在类上添加@Aspect注解
-
在类中定义方法,方法就是切面要执行的功能代码
在方法上添加aspectj中的通知注解,例如@Before
还需要指定切入点表达式execution()
@Before(value = "execution(public void com.cfl.service.impl.SomeServiceImpl.dosome(String,Integer))")
-
示例:
package com.cfl.aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; @Aspect public class MyAspect { @Before(value = "execution(public void com.cfl.service.impl.SomeServiceImpl.dosome(String,Integer))") public void dolog(){ DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日EHH点mm分ss秒"); System.out.println("现在是:"+dateFormat.format(new Date())); } }
-
-
在spring的配置文件中声明对象,把对象交给spring容器统一管理
声明对象可以使用注解或者xml配置文件
-
声明目标对象
-
声明切面类对象
-
声明aspectj框架中的自动代理生成器标签。
自动代理生成器:用来完成代理对象的自动创建功能
-
配置文件示例:
<?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 https://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="someServiceImpl" class="com.cfl.service.impl.SomeServiceImpl"/> <bean id="myAspect" class="com.cfl.aspect.MyAspect"/> <aop:aspectj-autoproxy/> </beans>
-
-
创建测试单元测试
-
代码示例:
package com.cfl; import com.cfl.service.SomeService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01(){ String config="classpath:applicationContext.xml"; ApplicationContext applicationContext=new ClassPathXmlApplicationContext(config); SomeService prothy = (SomeService) applicationContext.getBean("someServiceImpl"); prothy.dosome("lisi",23); System.out.println("proxy:"+prothy.getClass().getName()); } }
-