我们经常会在自己的项目中使用properties文件来集中管理各类信息,比如各类连接串..
为了在代码中引入配置文件,spring提供了两种引入方式
1、通过xml加载
<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->
<bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
</bean>
或者是
<!-- 与上面的配置等价,下面的更容易理解 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->
<array>
<value>classpath:conn.properties</value>
</array>
</property>
</bean>
2、通过注解方式加载
<!-- 第二种方式是使用注解的方式注入,主要用在java代码中使用注解注入properties文件中相应的value值 -->
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样
<array>
<value>classpath:public.properties</value>
</array>
</property>
</bean>
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
private String filePath;
@Value("#{prop.filePath}")
//@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=filePath的对应的value值
public void setFilePath(String filePath) {
this.filePath = filePath;
}