1、业务接口和实现类
UserService接口
package com.service;
public interface UserService {
public void add();
public void delete();
public int update();
public String select();
}
UserServiceImpl实现类
package com.service;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service("userService") //注册bean交给IOC管理
@Scope("singleton") //设置为单例模式
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加一个用户...");
}
@Override
public void delete() {
int res = 10/0; //制造异常
System.out.println("异常!");
}
}
2、定义两个切面(增强类)
可以使用Order配置增强类的优先级,属性值越小优先级越高!
PriorityAspect切面
@Component("proxyAspect") //注册bean交给IOC管理
@Aspect //切面
@Order(1)
public class PriorityAspect {
@Before("execution(* com.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("=====PriorityAspect前置通知=====");
}
}
DiyAspect切面
package com.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect //定义切面
@Component("diyAspect") //注册bean
@Order(3) //用于区分多个增强类,越小越先执行
public class DiyAspect {
//定义切点,当然可以不定义直接在增强方法上配置全路径也行。
@Pointcut("execution(* com.service.UserServiceImpl.*(..))")
public void point(){
}
@Before(value = "point()")
public void before(){
System.out.println("=====DiyAspect前置通知=====");
}
@After(value = "point()")
public void after(){
System.out.println("=====DiyAspect后置通知=====");
}
@AfterReturning(value = "point()")
public void afterReturning(){
System.out.println("=====后置返回通知=====");
}
@AfterThrowing(value = "point()")
public void afterThrowing(){
System.out.println("=====异常通知=====");
}
@Around(value = "point()")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("=====前置环绕通知=====");
jp.proceed(); //类似过滤器放行
System.out.println("=====后置环绕通知=====");
}
}
3、编写配置类取代XML配置文件
package com.utils;
import com.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration //配置文件
@ComponentScan("com.*") //扫描注解并启用注解支持
@EnableAspectJAutoProxy //开启aop自动代理对象
public class SpringConfig {
@Bean //实例化bean对象
public UserServiceImpl getUserServiceImple(){
return new UserServiceImpl();
}
}
4、测试
@Test
public void test1(){
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
userService.add();
userService.delete(); //异常
}