第一种配置方式 @Value("#{id名称.变量名}")
db.properties文件
yyf_name=liu
yyf_password=123
在SpringMVC.xml文件中加入
<util:properties id="idConfig" location="classpath:db.properties" />
controller中(自行创建controller的类文件,注解不限制为controller,但是必须有)
@Controller("userController")
public class UserController {
@Value("#{dbConfig.yyf_name}")
private String name;
@RequestMapping(value = "/user.do")
public Void userController(){//查看控制台输出liu
System.out.println(name);
}
}
第二种配置方式 @Value("${变量名}")
db.properties文件同上,在SpringMVC.xml文件中加入
<context:property-placeholder ignore-unresolvable="true" location="classpath:db.properties" />
controller中
@Controller("userController")
public class UserController {
@Value("${yyf_password}")
private String password;
@RequestMapping(value = "/user.do")
public Void userController(){//查看控制台输出123
System.out.println(password);
}
}
第三种配置方式 @Value("${变量名}")--PropertyPlaceholderConfigurer的bean
三个配置文件如下
spring-properties.xml中引入PropertyPlaceholderConfigurer这个bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
" default-lazy-init="false">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:db.properties</value>
</list>
</property>
</bean>
</beans>
在SpringMVC.xml文件中加入
<import resource="spring-properties.xml"/>
controller中
@Controller
public class UserController {@Value("${yyf_name}")
private String name;
@Value("${yyf_password}")
private String password;
@RequestMapping("/user.do")
public void userController(){
//查看控制台输出 姓名:liu密码:123
System.out.println("姓名:"+name+"密码:"+password);
}
}
这种方式虽然繁琐,但是做大型项目的时候配置文件非常多,这种方式方便管理配置文件。
第一次写博客,各位大佬多提意见!