Spring加载properties文件有两种方式,一种是通过xml的方式,另外一种是通过注解直接注入的方式。
方式一:通过xml配置的方式
首先,创建一个 jdbc.properties 文件,内容如下:
user=root
password=123456
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
然后在xml配置文件中导入这个配置文件。
在xml中也有两种方式引入外部properties文件
第一种是:通过 context:property-placeholder 标签引入,location的值是配置文件的地址
<context:property-placeholder location=“classpath:jdbc.properties”/>
第二种是:配置 PropertyPlaceholderConfigurer 这个类的bean实例
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,我们可以在下面配好多个properties文件 -->
<array>
<value>classpath:jdbc.properties</value>
</array>
</property>
</bean>
配置完成之后,我们就可以通过 ${key} 获取配置文件中对应key的值
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="driverClass" value="${driverClass}"/>
</bean>
方式二:通过注解的方式注入
通过注解的方式,首先需要在xml配置文件中,配置 PropertiesFactoryBean 这个类的实例,他的参数与方式一种的配置是一样的。
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath:jdbc.properties</value>
</array>
</property>
</bean>
配置完这个后就可以通过 @Value注解将配置文件中对应的值注入到指定的属性中。
@Component
public class Bird {
private String name;
@Value("#{prop.password}") // prop 是xml中配置PropertiesFactoryBean的bean的id
public void setName(String name) {
System.out.println(name + "正在注入中。。。。。。");
this.name = name;
}
}
测试一下,结果如下