1. 程式人生 > >@Aspect建立簡單切面

@Aspect建立簡單切面

1.首先,要使用@Aspect註解需要引入依賴

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.0</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.0</version>
</dependency>

2.開啟自動自動代理功能

2.1建立切面


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAspect {

    @Pointcut("execution(* com.example.demo.TestController.getMessage(..))")
    public void perform(){

    }

    @Before("perform()")
    public void beforeRun(){
        System.out.println("before do it");
    }

}

 

package com;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
//自動代理啟用
@EnableAspectJAutoProxy
public class Config {
    @Bean
    public MyAspect aspect(){
        return new MyAspect();
    }
}

 

在執行com.example.demo.TestController.getMessage()方法之前都會先呼叫beforeRun方法。