Spring Boot
这里使用的Spring Boot 2.0.3, 1.5.x的版本会有所不同,请查找API文档明确其中差异。
分类的配置信息
在Java项目中,为了灵活,总是有各类不同的配置项。在Spring Boot项目中,这些配置项都被放入了application.properties或者application.yml中去。也可以自定义各类的配置信息。这些配置信息为了简便灵活,都是将同种配置使用相同的前缀,用以区别使用。
具体方案
基于Spring Boot的@ConfigurationProperties和@EnableConfigurationProperties来使用不同的前缀,将这些配置信息读取到不同的Bean中。
目前的配置信息,默认放在application.properites下:
local.port=1090
local.host=127.0.0.1
remote.name=Jack Home
remote.host=abc.efg.com
这里将local读取LocalBean, remote的信息读取到RemoteBean。具体做法如下:
@ConfigurationProperties(prefix="local")
public class LocalBean {
private String port;
private String host;
}
另外一个Bean的定义如下:
@ConfigurationProperties(prefix="remote")
public class RemoteBean {
private String name;
private String host;
}
用以分别存储两者的配置信息。
启用ConfigurationProperties
使用@EnableConfigurationProperties来启动Spring Boot的开关,具体的示例代码如下:
@ComponentScan
@EnableConfigurationProperties(value= {LocalBean.class, RemoteBean.class})
public class Springboot3Application {
SpringApplication.run(Springboot3Application .class, args);
LocalBean local = (LocalBean)context.getBean(LocalBean.class);
RemoteBean remote = (RemoteBean)context.getBean(RemoteBean.class);
System.out.println("Local:" + local.getHost() + "," + local.getPort());
System.out.println("Remote:" + remote.getHost() + "," + remote.getName());
}
默认的配置文件
在配置文件未定指定的情况,Spring Boot应用默认会去读取application.properties或者applicaiton.yml文件中的信息,作为配置信息的来源。这个是默认的设置,无需开发者自行设计和干预。
自定义的配置文件
如何使用自定义的配置文件,则可以使用@PropertySource来引入具体的配置文件,使用示例如下:
@Configuration
@PropertySource(value = { "classpath:sysconfig.properties" }, encoding = "utf-8")
@ConfigurationProperties(prefix="remote")
public class RemoteBean {
private String name;
private String host;
}
自定义下的SpringBootApplication
在Spring Boot应用中,可以使用@SpringBootApplication来替代上述的两个标注,从而实现同样的功能, 首先来看看其定义:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
//.......
}
从上述定义中可以发现,直接使用SpringBootApplication的标注,简洁的使用方式如下:
@SpringBootApplication
public class Springboot3Application {
SpringApplication.run(Springboot3Application .class, args);
}
皆可实现类似的分类配置的目的。
@EnableConfigurationProperties
此标注基于测试中的使用来说,只能支持默认的application.properties/application.yml,无法直接使用自定义的配置文件。
@EnableConfigurationProperties(value= {LocalBean.class, RemoteBean.class})
总结
在本文中介绍了两种不同的配置方式,一种是基于默认的application.properties/application.yml方式来进行,另外一种是基于自定义的配置文件来进行。