Spring 运作原理
1.@SpringBootApplication: @configure, @componentscan @enableautoconfiguration
- 核心功能 @EnableAutoConfiguration
- –>@import—>enableAutoconfiguationImportSelctor—>SpringFactoryLoader.loadFactoryNames—>sprng.factories
新建配置类,写好配置项和默认的配置值,指明配置项前缀。
@Data
@ConfigurationProperties(prefix = "sxw.elasticsearch")
public class ElasticSearchProperties {
private String clusterName = "elasticsearch";
private String clusterNodes = "127.0.0.1:9300";
private String userName = "elastic";
private String password = "changeme";
}
新建自动装配类,使用@Configuration和@Bean来进行自动装配。
@Slf4j
@Configuration
@EnableConfigurationProperties(ElasticSearchProperties.class)
public class ElasticSearchAutoConfiguration implements DisposableBean{
private TransportClient transportClient;
@Resource
private ElasticSearchProperties properties;
@Bean
@ConditionalOnMissingBean(TransportClient.class)
public TransportClient transportClient() {
log.debug("=======" + properties.getClusterName());
log.debug("=======" + properties.getClusterNodes());
log.debug("=======" + properties.getUserName());
log.debug("=======" + properties.getPassword());
log.info("开始建立es连接");
transportClient = new PreBuiltXPackTransportClient(settings());
TransportAddress[] transportAddresses= Arrays.stream(properties.getClusterNodes().split(",")).map (t->{
String[] addressPortPairs = t.split(":");
String address = addressPortPairs[0];
Integer port = Integer.valueOf(addressPortPairs[1]);
try {
return new InetSocketTransportAddress(InetAddress.getByName(address), port);
} catch (UnknownHostException e) {
log.error("连接ElasticSearch失败", e);
throw new RuntimeException ("连接ElasticSearch失败",e);
}
}).collect (Collectors.toList ()).toArray (new TransportAddress[0]);
transportClient.addTransportAddresses(transportAddresses);
return transportClient;
}
private Settings settings() {
return Settings.builder()
.put("cluster.name", properties.getClusterName())
.put("xpack.security.user", properties.getUserName() +
":" + properties.getPassword())
.build();
}
@Override
public void destroy() throws Exception {
log.info("开始销毁Es的连接");
if (transportClient != null) {
transportClient.close();
}
}
}
本类主要对TransportClient类进行自动配置;
@ConditionalOnMissingBean 当Spring容器中没有TransportClient类的对象时,调用transportClient()创建对象;
关于更多Bean的条件装配用法请自行查阅Spring Boot相关文档
新建spring.factories文件,指定Starter的自动装配类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.sxw.commons.data.es.starter.ElasticSearchAutoConfiguration
spring.factories文件位于resources/META-INF目录下,需要手动创建;
org.springframework.boot.autoconfigure.EnableAutoConfiguration后面的类名说明了自动装配类,如果有多个 ,则用逗号分开;
使用者应用(SpringBoot)在启动的时候,会通过org.springframework.core.io.support.SpringFactoriesLoader读取classpath下每个Starter的spring.factories文件,加载自动装配类进行Bean的自动装配;