- 准备好接口和实现类
@Service
public interface AninmalService {
public void service();
}
@Service("dogService")
public class DogServiceImpl implements AninmalService{
@Autowired
public Dog dog;
@Override
public void service() {
System.out.println("dog");
}
}
- 切面类
@Aspect
public class MyAspect {
@Pointcut("execution(* com.yueqin.service.impl.DogServiceImpl.service(..))")
public void pointCut(){}
@Before("pointCut()")
public void before(){
System.out.println("before");
}
@After("pointCut()")
public void after(){
System.out.println("after");
}
@AfterReturning("pointCut()")
public void afterReturning(){
System.out.println("afterReturning");
}
@AfterThrowing("pointCut()")
public void afterThrowing(){
System.out.println("afterThrowing");
}
}
- 配置类
@Configuration
@ComponentScan(basePackages = {"com.yueqin"})
@EnableAspectJAutoProxy
@PropertySource(value={"classpath:application.properties"})
public class BootConfig {
@Bean
public MyAspect initMyAspect(){
return new MyAspect();
}
}
- 测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BootConfig.class);
AninmalService aninmalService = (AninmalService) context.getBean("dogService");
aninmalService.service();
}
}
- 测试afterRetruning结果
- 测试afterThrowing结果
6.1 构造异常
@Service("dogService")
public class DogServiceImpl implements AninmalService{
@Autowired
public Dog dog;
@Override
public void service() throws Exception {
System.out.println("dog");
throw new Exception("这是构造的异常");
}
}
6.2 测试类
public class MyTest {
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(BootConfig.class);
AninmalService aninmalService = (AninmalService) context.getBean("dogService");
aninmalService.service();
}
}
6.3 再次运行测试类的结果
7. 测试传参
7.1 接口实现类
@Service("dogService")
public class DogServiceImpl implements AninmalService{
@Autowired
public Dog dog;
@Override /*传参Cat*/
public void service(Cat cat) throws Exception {
System.out.println("dog");
throw new Exception("这是构造的异常");
}
}
7.2 切面类
@Before("pointCut() && args(cat)") //args(参数名)方式来引入参数, 参数名需要与下面声明的参数名称一致
public void before(JoinPoint joinPoint,Cat cat){ //Cat cat表示声明参数类型和名称,JoinPoint连接点用来获取参数回调信息
System.out.println(cat);
System.out.println(joinPoint.getTarget().toString()); //joinpoint可以获取target对象。
System.out.println("before");
}
7.3 测试结果
-
注意事项:
8.1 必须在configuration的配置类中加入@EnableAspectJAutoProxy否则AOP不会生效8.2 在configuration配置类注入MyAspect Bean的原因是方便快速找到Aop 的Bean的配置。
当然取消在configuration配置类中的Bean注入,然后在MyAspect 类上方加入component注解一样可以将切面类注入到Spring容器 【已测试】。