1、先导入aspectj依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
2、创建目标类和目标接口
public interface DoService {
public void DoServiceAop(String name);
}
public class DoServiceImpl implements DoService {
@Override
public void DoServiceAop(String name) {
System.out.println(name + "执行了业务逻辑===========");
}
}
3、创建切面类,@Aspect表示该类是切面类,在容器中创建的时候会被创建成切面类。@Before表示在DoServiceAop方法执行前执行DoLogs方法。其中的value是该DoServiceAop所在的位置。
@Aspect
public class UntilTools {
@Before(value = "execution(public void com.aop.aspectj.service.DoService.DoServiceAop(String))")
public static void DoLogs(){
System.out.println("执行了日志记录" + new Date().toLocaleString());
}
}
4、编写配置xml文件。当扫明到aop:aspectj-autoproxy/标签的时候,会根据@Aspect和@Before注解生成代理对象。@Aspect就是切面类,@Before的execution就会声明代理对象和方法。
<bean id="Myaspect" class="com.aop.aspectj.service.UntilTools"/>
<bean id="Myservice" class="com.aop.aspectj.service.impl.DoServiceImpl"/>
<aop:aspectj-autoproxy/>
5、java调用
String config = "ApplicationConfig.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
DoService ds = (DoService) ac.getBean("Myservice");
ds.DoServiceAop("ljq");
输出
执行了日志记录2021-5-23 16:33:22
ljq执行了业务逻辑===========