1、在spring的xml配置文件中获取配置文件变量值
在applicationContext.xml中加载peiz配置文件,加入代码如下:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
使用方式:"${key}",举例如下:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
2、在Controller中获取.properties中的变量值,可以使用"@Value("${key}")" 来获取数值,但是其中会出现@Value获取不到值的状况。
原因: 只在applicationContext中添加了扫描,没有在SpringMVC对应的配置文件中扫描。
applicationContext加载的是父容器,,父容器在项目启动的时候就被加载了。SpringMVC对应的配置文件加载的是子容器,子容器可以访问父容器的对象,但是不能访问加载的配置文件。所以,如果想在SpringMVC中使用加载的配置文件,需要在SpringMVC对应的配置文件中添加相应的配置即可。
解决方案:
1、spring-mvc.xml中加入加载.properties的加载配置语句。举例如下
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:httpUrl.properties"/>
2、在Controller中取值
@Value("${getAllManufacturer}")
private String getAllManufacturerUrl;
3、在普通的Class文件中获取变量值
@Component
public class Constant {
@Value("${getToken}")
private String tokenUrl;
}
4、注意:如果class的静态变量值(static)是获取不到获取,解决举例如下:
@Component
public class Constant {
private static String tokenUrl;
private static String username;
private static String password;
@Value("${getToken}")
private void setTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
}
@Value("${login.username}")
private void setUsername(String username) {
this.username = username;
}
@Value("${login.password}")
private void setPassword(String password) {
this.password = password;
}
}