Spring加载Properties配置文件
相关文章链接:
观前提示:
IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Tomcat版本为9.0.12,postman版本为v7.27.1。
标题2.3.4.5测试用配置文件 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false
jdbc.username=root
jdbc.password=root
jdbc.pool.initialPoolSize=10
jdbc.pool.minPoolSize=5
jdbc.pool.maxPoolSize=40
jdbc.pool.maxIdleTime=20
jdbc.pool.checkoutTimeout=10000
1.@PropertySource注解
配置文件 test.properties
id=01
name=zhangsan
age=18
配置文件加载类 TestProperties .java
package com.example.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = {
"classpath:config/test.properties"})
public class TestProperties {
@Value("id")
private String id;
@Value("name")
private String name;
@Value("age")
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "TestProperties{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
测试文件 TestController .java
package com.example.controller;
import com.example.config.TestProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
private TestProperties testProperties;
@RequestMapping(value = "/testProperties", method = RequestMethod.GET)
@ResponseBody
public String testProperties(){
return testProperties.toString();
}
}
使用postman发送请求,测试结果为
2.context:property-placeholder标签
2.1 参考配置
xml文件中配置参考如下
<context:property-placeholder location="/WEB-INF/config/jdbc.properties"/>
注意:取值时使用 ${}
2.2 例子
2.2.1 在xml中取值
<property name="driverClassNa