1、原始对象
UserServiceImpl.java
package com.yusian.service;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Override
public void login() {
System.out.println("UserServiceImpl.login");
}
}
2、切面类
注意事项:
- @Aspect定义当前类为切面类
- @Around定义当前方法为代理方法
- @Component使Spring自动创建当前类的实例对象
MyAspect.java
package com.yusian.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Around("execution(* *(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("before....");
Object ret = joinPoint.proceed();
System.out.println("after.....");
return ret;
}
}
3、配置类
注意事项:
- @Configuration定义当前类为Spring的配置类
- @EnableAspectJAutoProxy开启Aop自动动态代理
- @ComponentScan扫描自动加载的bean对象
AppConfig.java
package com.yusian.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan({"com.yusian.service", "com.yusian.aspect"})
public class AppConfig {
}
4、测试
@Test
public void aopTest() {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = (UserService) ctx.getBean("userServiceImpl");
userService.login();
}
执行结果:
before....
UserServiceImpl.login
after.....
Process finished with exit code 0