Spring 实践
读取配置文件
在开发中有一些因为环境不同,变量不同的值,如果写死到代码中后,修改起来成本很高,所以我们常常写到配置文件中,在更换对应值时,只需要更改配置文件里的值即可。(数据源配置、solr配置、redis配置、一些与其他项目对接的接口、白名单等)
1、首先,必须先加载properties配置文件,方式有两种,如下
-
(1)<context:property-placeholder location="classpath:jdbc.properties"/>
-
(2)<bean id="propertyConfigurer"
-
class= "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
-
<property name="location">
-
<value>/WEB-INF/configs/sqlServer1.properties</value>
<value>/WEB-INF/configs/sqlServer2.properties</value>
-
</property>
-
</bean>
第二种比较常用,加载多个配置文件时比较方便,明了。
2、引用变量
1、xml里引用 直接${jdbc.driver}引用即可
-
<bean id="dataSource"
-
class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
-
<property name="driverClassName">
-
<value>${jdbc.driver} </value>
-
</property>
-
<property name="url" >
-
<value>${jdbc.url} </value>
-
</property>
-
<property name="username" >
-
<value>${jdbc.user} </value>
-
</property>
-
<property name="password">
-
<value>${jdbc.pwd} </value>
-
</property>
-
</bean>
2、代码里引用
@Value注解读取 常用有两种方式
-
"#{prop.name}")(
-
private String name;
-
"${name}")(
-
private String name;