如何在SpringBoot中使用AutoConfiguration
本篇文章为大家展示了如何在SpringBoot 中使用AutoConfiguration,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
成都创新互联专注于企业网络营销推广、网站重做改版、黟县网站定制设计、自适应品牌网站建设、H5建站、成都商城网站开发、集团公司官网建设、成都外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为黟县等各大城市提供网站开发制作服务。
主要代码片段:
String[] selectImports(AnnotationMetadata annotationMetadata)方法中
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
getAutoConfigurationEntry方法中:
Listconfigurations = this.getCandidateConfigurations(annotationMetadata, attributes); protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List 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
Enumerationurls = 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, ListcurrentChilds) { 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呢
首先要在需要使用的项目中引入依赖
com.fayayo fim-registry-zookeeper 0.0.1-SNAPSHOT
然后配置参数
fim: register: address: 192.168.88.129:2181 timeout: 2000
如果不配置会有默认的参数
具体使用的时候只需要在Bean中注入就可以了,比如
@Autowired private Registry registry; public ListgetAll(){ List list=cache.get(KEY); if(CollectionUtils.isEmpty(list)){ list=registry.discover(); cache.put(KEY,list); } return list; }
springboot是什么
springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。
上述内容就是如何在SpringBoot 中使用AutoConfiguration,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
名称栏目:如何在SpringBoot中使用AutoConfiguration
分享URL:http://ybzwz.com/article/ieceep.html