標籤:

spring下動態註冊組件的一種簡單的解決思路

工作中,實現組件自動註冊的方法有不少,其中使用jdk自帶的 Service Provider Interface(SPI)也很簡單。如果你使用spring框架,我在這裡提供另外一種思路。依賴於spring的組件掃描和註冊功能,15行代碼不到實現自動註冊組件功能。最近一個項目中使用了這種方式,代碼非常簡單,目前看來沒有什麼大問題。

最終工程結構

定義組件介面

新建一個項目,定義介面。

package cn.xiaowenjie;/** * 組件介面類 * * @author 肖文傑 https://github.com/xwjie/DynamicComponentDemo * */public interface IComponent { String getName(); String getDescript(); int doSomeThing(int i, int j);}

另外,由於要依賴spring,所以把spring依賴放到這個公共的介面項目中,這樣其他實現介面的項目就不再需要單獨加依賴了。

實現自己的組件

非常簡單,新建一個項目。引入介面項目的依賴,實現介面即可。需要增加 Component 註解。

package cn.xiaowenjie;import org.springframework.stereotype.Component;/** * 測試組件1 * * @author 曉風輕 https://github.com/xwjie/DynamicComponentDemo * */@Componentpublic class MyComponent1 implements IComponent { public String getName() { return "COMP_ADD"; } public String getDescript() { return "返回值相加結果"; } public int doSomeThing(int i, int j) { return i + j; }}

主工程

新建主項目,讓spring找到所有實現了介面的組件即可。其實就2行代碼。需要加 required = false ,否則沒有任何組件的時候會報錯。

@Autowired(required = false)List<IComponent> components;

完整代碼:

package cn.xiaowenjie.controllers;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import cn.xiaowenjie.IComponent;import cn.xiaowenjie.beans.ResultBean;/** * 測試類 * * @author 肖文傑 https://github.com/xwjie/DynamicComponentDemo * */@RequestMapping("/comp")@RestControllerpublic class MainController { @Autowired(required = false) List<IComponent> components; /** * 查看所有組件 * * @return */ @GetMapping("/all") public ResultBean<List<IComponent>> all() { return new ResultBean<List<IComponent>>(components); } /** * 測試執行結果 * * @return */ @GetMapping("/exec") public ResultBean<List<String>> exec() { List<String> outputs = new ArrayList<String>(); if (components != null) { for (IComponent comp : components) { outputs.add("組件名:" + comp.getName() + ",執行結果:" + comp.doSomeThing(10, 3)); } } return new ResultBean<List<String>>(outputs); }}

在主工程引入實現的組件項目:

測試結果:

指定組件的順序

使用 @Order 註解即可。

@Component@Order(1)public class MyComponent2 implements IComponent

總結

使用spring的自動掃描註冊,實現起來非常簡單,最終發布的時候也很方便,把組件的工程打成jar包扔進去即可。

==============GITHUB=============

xwjie/DynamicComponentDemo

推薦閱讀:

jsonp跨域請求詳解——從繁至簡
Spring之CROS解決AJAX跨域問題
快速了解spring事務七種傳播方式、事務的4種隔離級別、臟讀、重複讀、幻讀;
Spring boot 進階之路
Spring Security(三) -- JWT驗證原理(上)

TAG:Spring |