您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在SpringBoot 中使用AutoConfiguration,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
主要代碼片段:
String[] selectImports(AnnotationMetadata annotationMetadata)方法中
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
getAutoConfigurationEntry方法中:
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes); protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct."); return configurations; }
最后會通過SpringFactoriesLoader.loadSpringFactories去加載META-INF/spring.factories
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories"); LinkedMultiValueMap result = new LinkedMultiValueMap();
while(urls.hasMoreElements()) { URL url = (URL)urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); Iterator var6 = properties.entrySet().iterator(); while(var6.hasNext()) { Entry<?, ?> entry = (Entry)var6.next(); String factoryClassName = ((String)entry.getKey()).trim(); String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue()); int var10 = var9.length; for(int var11 = 0; var11 < var10; ++var11) { String factoryName = var9[var11]; result.add(factoryClassName, factoryName.trim()); } } }
ZookeeperAutoConfiguration
我們來實現一個ZK的AutoConfiguration
首先定義一個ZookeeperAutoConfiguration類
然后在META-INF/spring.factories中加入
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.fayayo.fim.zookeeper.ZookeeperAutoConfiguration
接下來我們看看具體的實現:
@ConfigurationProperties(prefix = "fim.register") @Configuration public class URLRegistry { private String address; private int timeout; private int sessionTimeout; public String getAddress() { if (address == null) { address = URLParam.ADDRESS; } return address; } public void setAddress(String address) { this.address = address; } public int getTimeout() { if (timeout == 0) { timeout = URLParam.CONNECTTIMEOUT; } return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getSessionTimeout() { if (sessionTimeout == 0) { sessionTimeout = URLParam.REGISTRYSESSIONTIMEOUT; } return sessionTimeout; } public void setSessionTimeout(int sessionTimeout) { this.sessionTimeout = sessionTimeout; } } @Configuration @EnableConfigurationProperties(URLRegistry.class) @Slf4j public class ZookeeperAutoConfiguration { @Autowired private URLRegistry url; @Bean(value = "registry") public Registry createRegistry() { try { String address = url.getAddress(); int timeout = url.getTimeout(); int sessionTimeout = url.getSessionTimeout(); log.info("init ZookeeperRegistry,address[{}],sessionTimeout[{}],timeout[{}]", address, timeout, sessionTimeout); ZkClient zkClient = new ZkClient(address, sessionTimeout, timeout); return new ZookeeperRegistry(zkClient); } catch (ZkException e) { log.error("[ZookeeperRegistry] fail to connect zookeeper, cause: " + e.getMessage()); throw e; } } }
ZookeeperRegistry部分實現:
public ZookeeperRegistry(ZkClient zkClient) { this.zkClient = zkClient; log.info("zk register success!"); String parentPath = URLParam.ZOOKEEPER_REGISTRY_NAMESPACE; try { if (!zkClient.exists(parentPath)) { log.info("init zookeeper registry namespace"); zkClient.createPersistent(parentPath, true); } //監聽 zkClient.subscribeChildChanges(parentPath, new IZkChildListener() { //對父節點添加監聽子節點變化。 @Override public void handleChildChange(String parentPath, List<String> currentChilds) { log.info(String.format("[ZookeeperRegistry] service list change: path=%s, currentChilds=%s", parentPath, currentChilds.toString())); if(watchNotify!=null){ watchNotify.notify(nodeChildsToUrls(currentChilds)); } } }); ShutDownHook.registerShutdownHook(this); } catch (Exception e) { e.printStackTrace(); log.error("Failed to subscribe zookeeper"); } }
具體使用
那么我們怎么使用自己寫的ZookeeperAutoConfiguration呢
首先要在需要使用的項目中引入依賴
<dependency> <groupId>com.fayayo</groupId> <artifactId>fim-registry-zookeeper</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
然后配置參數
fim: register: address: 192.168.88.129:2181 timeout: 2000
如果不配置會有默認的參數
具體使用的時候只需要在Bean中注入就可以了,比如
@Autowired private Registry registry; public List<URL> getAll(){ List<URL>list=cache.get(KEY); if(CollectionUtils.isEmpty(list)){ list=registry.discover(); cache.put(KEY,list); } return list; }
springboot一種全新的編程規范,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程,SpringBoot也是一個服務于框架的框架,服務范圍是簡化配置文件。
上述內容就是如何在SpringBoot 中使用AutoConfiguration,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。