1.加入Aspectj的maven依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
2.编写接口(jdk动态代理需要实现接口)
package org.example.service;
public interface SomeService {
void doSome();
}
3.编写接口实现类并将对象交给Spring容器管理
package org.example.service.impl;
import org.example.service.SomeService;
import org.springframework.stereotype.Component;
@Component("someServiceImpl")
public class SomeServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("HelloWorld");
}
}
4.编写切面 声明切面(@Aspect) 声明切入点(execution(* org.example.service.impl.SomeServiceImpl.doSome(…))) 声明切入时间(@Before) 并将对象交给Spring容器管理
package org.example.util;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component("serviceTools")
@Aspect
public class ServiceTools {
@Before(value = "execution(* org.example.service.impl.SomeServiceImpl.doSome(..))")
public void doLog(){
System.out.println("time:"+new Date());
}
}
5.配置applicationContext.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
http://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
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--声明组件扫描器-->
<context:component-scan base-package="org.example.bean"></context:component-scan>
<context:component-scan base-package="org.example.service.impl"></context:component-scan>
<context:component-scan base-package="org.example.util"></context:component-scan>
<!--开启aop自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
6.测试
@Test
public void TestAspect(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
SomeService someService = (SomeService) applicationContext.getBean("someServiceImpl");
someService.doSome();
}
结果:
time:Mon Mar 01 10:42:17 CST 2021
HelloWorld