对 Spring 内里的 Properties 不领略的开拓者大概会以为有点乱,主要是因为设置方法许多种,利用方法也许多种。
本文不是道理阐明、源码阐明文章,只是但愿可以辅佐读者更好地领略和利用 Spring Properties。
Properties 的利用
本文的读者都是利用过 Spring 的,先来看看 Properties 是怎么利用的,Spring 中常用的有以下几种利用方法:
1. 在 xml 设置文件中利用
即自动替换 ${}
内里的值。
<bean id="xxx" class="com.javadoop.Xxx"> <property name="url" value="${javadoop.jdbc.url}" /> </bean>
2. 通过 @Value 注入利用
@Value("${javadoop.jdbc.url}") private String url;
3. 通过 Environment 获取
此法有需要留意的处所。并不是所有的设置方法都支持通过 Environment 接口来获取属性值,亲测只有利用注解 @PropertySource 的时候可以用,不然会获得 null,至于怎么设置,下面顿时就会说。
@Autowired private Environment env; public String getUrl() { return env.getProperty("javadoop.jdbc.url"); }
假如是 Spring Boot 的 application.properties 注册的,那也是可以的。
Properties 设置
前面我们说了怎么利用我们设置的 Properties,那么该怎么设置呢?Spring 提供了许多种设置方法。
1. 通过 xml 设置
下面这个是最常用的设置方法了,许多项目都是这么写的:
<context:property-placeholder location="classpath:sys.properties" />
2. 通过 @PropertySource 设置
前面的通过 xml 设置非经常用,可是假如你也有一种要没落所有 xml 设置文件的激动的话,你应该利用以下方法:
@PropertySource("classpath:sys.properties") @Configuration public class JavaDoopConfig { }
留意一点,@PropertySource 在这里必需搭配 @Configuration 来利用,详细不展开说了。
3. PropertyPlaceholderConfigurer
假如读者见过这个,也不必以为奇怪,在 Spring 3.1 之前,常常就是这么利用的:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:sys.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> <!-- 这里可以设置一些属性 --> </bean>
虽然,我们也可以用相应的 java configuration 的版本:
@Bean public PropertyPlaceholderConfigurer propertiess() { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")}; ppc.setLocations(resources); ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; }
4. PropertySourcesPlaceholderConfigurer
到了 Spring 3.1 的时候,引入了 PropertySourcesPlaceholderConfigurer,这是一个新的类,留意看和之前的 PropertyPlaceholderConfigurer 在名字上多了一个 Sources,所属的包也纷歧样,它在 Spring-Context 包中。
在设置上倒是没有什么区别:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:sys.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> <!-- 这里可以设置一些属性 --> </bean>
也来一个 java configuration 版本吧:
@Bean public PropertySourcesPlaceholderConfigurer properties() { PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer(); Resource[] resources = new ClassPathResource[]{new ClassPathResource("sys.properties")}; pspc.setLocations(resources); pspc.setIgnoreUnresolvablePlaceholders(true); return pspc; }
Spring Boot 相关
Spring Boot 真的是好对象,开箱即用的感受实在是太好了。这里简朴先容下相关的内容。
快速生成一个 Spring Boot 项目:https://start.spring.io/
application.properties
我们每个项目都默认有一个 application.properties 文件,这个设置文件不需要像前面说的那样举办注册,昆山软件开发,Spring Boot 会帮我们自动注册。