在pom文件中引入aop功能
org.springframework
spring-aspects
4.3.12.RELEASE
现在想给某个方法在执行之前、之后、结果返回和发生异常时打印出相关信息
public class AOP {
public int div(int x, int y){
return x/y;
}
}
首先定义需要打印信息的方法,在spring中此类方法被称为切面,在注解中通过@Aspect标记一个方法是否为切面
@Aspect
public class AopLog {
}
切点代表了要给哪个方法添加通知的功能,写法为execution(方法的全路径),*(…)表示给该类下所有方法,任意参数都添加通知
execution(public int com.xxx.aop.AOP.*(..))
也可以通过@PointCut给某个方法标记为切点,这样在其他需要切点表达式的地方可以直接写切点方法名
@Pointcut("execution(public int com.xxx.aop.AOP.*(..))")
public void pointCut(){}
在方法运行之前、运行之后、返回值、发生异常时所执行的方法被称为通知,spring注解中通过@Before、@After、 @AfterReturning和 @AfterThrowing标记,通过添加JointPoint参数可以获取到方法的所有信息,该参数必须放在第一位。
@Before("execution(public int com.xxx.aop.AOP.*(..))")
public void before(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println("div before...{"+ Arrays.asList(args)+"}"+joinPoint.getSignature().getName());
}
@After("pointCut()")
public void after(){
System.out.println("div after...");
}
@AfterReturning(value = "pointCut()", returning = "result")
public void returned(Object result){
System.out.println("div return..."+result);
}
@AfterThrowing(value = "com.xxx.aop.AopLog.pointCut()", throwing = "except")
public void except(Exception except){
System.out.println("exception..."+except.getMessage());
}
当业务类和切面类都写好以后,需要在配置文件中开启AOP功能,@EnableAspectJAutoProxy注解代表spring会去扫描被@Aspect注解标记的类,并将指定的方法织入到指定的位置。
@Configuration
@Import({AopLog.class})
@EnableAspectJAutoProxy
public class AopConfig {
@Bean
public AOP aop(){
return new AOP();
}
}
首先创建一个数据源,可以是任意类型的数据源
@Bean
public DataSource dataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:///test");
dataSource.setUser("root");
dataSource.setPassword("root");
return dataSource;
}
开启事务管理功能,添加@EnableTransactionManagement注解
@Configuration
@EnableTransactionManagement
public class AopConfig {}
将事务管理器添加进spring容器中
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
在需要使用事务的方法或类上标记 @Transactional即可给指定的类或方法添加事务
@Transactional
public void insert(){
int i = 1/0;
}