Spring註解版之AOP和事務

pom文件配置

在pom文件中引入aop功能

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.12.RELEASE</version>
        </dependency>

業務類

現在想給某個方法在執行之前、之後、結果返回和發生異常時打印出相關信息

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());
    }

@EnableAspectJAutoProxy

當業務類和切面類都寫好以後,需要在配置文件中開啓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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章