我正在尝试使用Spring 4.1读取属性文件。我的班级看起来或多或少像官方example,我想把它自动装入我的其他班级。
@Configuration
@PropertySource(value = "file:C:/asd1.properties")
public class PropertiesUtil {
@Autowired
private Environment env;
public String getStuff() {
return env.getProperty("stuff");
}
}
和
@Autowired
private PropertiesUtil propertiesUtil;
public void setPropertiesUtil(PropertiesUtil propertiesUtil) {
this.propertiesUtil = propertiesUtil;
}
但是,PropertySource注释似乎被忽略了。我可以在getStuff()
和env
存在断点,但getProperty
返回null。此外,如果文件实际上不存在,Spring也不会抱怨。
我错过了什么?
答案 0 :(得分:0)
1)属性文件的内容:
stuff=hello
2)Spring-config文件:
<?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">
<context:component-scan base-package="com.spring.concept" />
<bean id="test" class="com.spring.concept.Testing" />
</beans>
3)Testing.java
package com.spring.concept;
import org.springframework.beans.factory.annotation.Autowired;
public class Testing {
@Autowired
private PropertiesUtil propertiesUtil;
public void setPropertiesUtil(PropertiesUtil propertiesUtil) {
this.propertiesUtil = propertiesUtil;
}
public void print(){
System.out.println("Hello world!!");
System.out.println(propertiesUtil.getStuff());
}
}
4)PropertiesUtil.java与您发布的内容类似 5)在pom.xml中,添加了这两个依赖项
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
5)主要方法:
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-config.xml");
Testing test=(Testing)ctx.getBean("test");
test.print();
}
6)输出:
你好世界!!
喂
检查
<context:component-scan>
在你的spring配置文件和asd1.properties文件的内容中。