初探spring boot Enable能力

       spring boot 由於其超強的整合能力和強大的社區生態,已經漸漸成爲java項目開發必備框架。

       使用過springboot的同學們應該都很清楚,很多第三方組件與springboot集成時只需要添加一個@EnableXXX註解,就可以在項目中使用。下面使用springboot的Enable來實現一個記錄方法調用次數的例子。

       第一步. 定義EnableMethod註解類

@Import(MethodConfiguration.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableMethod {
}
@Import(MethodConfiguration.class) 這行代碼告訴springboot需要雲解析MethodConfiguration這個類。

第二步. MethodConfiguration

@Configurable
@Aspect
public class MethodConfiguration {

    static Map<String, Integer> map = new HashMap<>();

    @Pointcut("@annotation(com.zsc.spring.method.annotions.MethodStatistics)")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void before(JoinPoint point) {
        String methodName = point.getSignature().getName();
        System.out.println(String.format("invoke method %s", methodName));
        Integer count = map.get(methodName);
        if(null == count) {
            map.put(methodName, 1);
        } else {
            map.put(methodName, ++count);
        }
        System.out.println(map.get(methodName));
    }
}

@Configuration:告訴springboot該類作爲一個配置類注入到spring容器中

@Aspect: 將MethodConfiguration定義成一個切面類,攔截所有添加MethodStatistics註解方法,最終注入到spring容器中

第三步:將該工程使用maven 打包成jar包,以便使用者引入

第四步:需要使用springboot項目中引入

<dependency>
            <groupId>com.zsc.spring.method</groupId>
            <artifactId>spring-method</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

第五步:Application類添加@EnableMethod註解

@SpringBootApplication
@EnableMethod
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);
    }
}

第六步:添加測試接口,並添加@MethodStatistics註解

@RestController
public class HelloWorldController {

    @RequestMapping(value = "hello")
    @MethodStatistics
    public String hello() {
        return "hello spring boot enable";
    }
}

第七步:啓動項目,訪問http://localhost:8080/hello接口,觀察控制檯信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章