Spring Property-01-入门使用
2017年8月8日大约 2 分钟
多个属性文件问题
情境
文件路径如下:
├─src
│ ├─main
│ │ ├─java
│ │ │ └─com
│ │ │ └─ryo
│ │ │ └─spring
│ │ │ └─property
│ │ │ User.java
│ │ │
│ │ └─resources
│ │ one.properties
│ │ spring-beans-one.xml
│ │ spring-beans-two.xml
│ │ two.properties
│ │
│ └─test
│ └─java
│ UserTest.java
- one.properties
oneName=one
- two.properties
twoName=two
- spring-beans-one.xml
- spring-beans-two.xml
- User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- UserTest.java
测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring-beans-one.xml",
"classpath:spring-beans-two.xml",
})
public class UserTest {
@Autowired
@Qualifier("one")
private User one;
@Autowired
@Qualifier("two")
private User two;
@Test
public void infoTest() {
System.out.println(one.getName());
System.out.println(two.getName());
}
}
Error
运行测试案例,报错如下:
...
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'two' defined
in class path resource [spring-beans-two.xml]: Could not resolve placeholder 'twoName' in string value "${twoName}";
nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'twoName' in string value "${twoName}"
...
原因
解决方案
一、ignore-unresolvable
引入属性文件时,指定 ignore-unresolvable="true"
。注意:所有的属性文件引入都需要显示指定。
如:
二、同时引入多个属性文件
属性文件不要在单个文件一个个引入。直接在最后统一引入。可使用如下方式:
(支持 RegEx 匹配,只需要在一个文件中引入即可,其他文件移除。)
也可以采用下面的方式(二者本质是等价的)
classpath:one.properties
classpath:two.properties
file:/opt/demo/config/demo-remote.properties-->
解析 properties 文件
一、直接注入到bean中
二、使用 @Value
- UserTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:spring-beans-one.xml",
"classpath:spring-beans-two.xml",
})
public class UserTest {
@Value("${oneName}")
private String oneName;
@Test
public void oneNameTest() {
System.out.println(oneName);
}
}
结果:
one
参考文档
贡献者
binbin.hou