Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在Spring中使用@value从属性中获取值_Spring_Spring Annotations - Fatal编程技术网

无法在Spring中使用@value从属性中获取值

无法在Spring中使用@value从属性中获取值,spring,spring-annotations,Spring,Spring Annotations,我有一个使用spring的项目模板,需要属性文件中的值,但当我运行程序时,该值为null。这是我的密码: 属性文件包含:TOWN=Cluj 公共类基类测试{ @值(“${TOWN}”) 公共字符串字符串值; @试验前 测试前公共无效(){ ApplicationContext上下文=新的ClassPathXmlApplicationContext(“beans.xml”); Student=context.getBean(“studentBean”,Student.class); student

我有一个使用spring的项目模板,需要属性文件中的值,但当我运行程序时,该值为null。这是我的密码: 属性文件包含:TOWN=Cluj

公共类基类测试{
@值(“${TOWN}”)
公共字符串字符串值;
@试验前
测试前公共无效(){
ApplicationContext上下文=新的ClassPathXmlApplicationContext(“beans.xml”);
Student=context.getBean(“studentBean”,Student.class);
student.displayName();
student.displayTown();
System.out.println(stringValue);//->这是空的
}
}
bean文件:


公共班级学生{
私有字符串名称;
私人弦镇;
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共字符串getTown(){
返回城镇;
}
城市公共空间(字符串城市){
this.town=城镇;
}
public void displayName(){
System.out.println(“名称:”+Name);
}
公营城市(){
System.out.println(“镇:+镇);
}
}
在BaseTest中,当调用
displayTown(
)方法时,属性文件中的值起作用,但如果尝试在
BaseTest
中将该值用作变量,则该值为空。
你能帮我吗?

正如你所确认的
BaseTest
只是一门普通的课程。值不会自动注入

在xml中

<context:property-placeholder location="classpath:stable.properties"/>
扫描类路径以查找将被删除的带注释的组件 自动注册为SpringBeans。默认情况下,提供了弹簧 @组件、@Repository、@Service、@Controller、@RestController、, @将检测ControllerAdvice和@Configuration原型

你不需要在课堂上使用
@Value(${TOWN}”)


添加任何一个配置,它将自动扫描您的类,如果它在
com.base
package

下提供,那么在BaseTest顶部是否有任何注释,如@configuration等?不,这是BaseTest公共类BaseTest的声明{BaseTest类Spring的基本包是什么?Spring不会将值注入任意对象。只注入Spring bean。您的测试不是Spring bean,因此您不能期望Spring在其中注入任何内容。请检查以下内容:
<context:component-scan base-package="com.base" />
<bean name="studentBean" class="com.model.Student">
    <property name="name" value="MyName"/>
    <property name="town" value="${TOWN}"/>
</bean>
<bean name="baseTestBean" class="classpath.BaseTest">
    <property name="stringValue" value="${TOWN}"/>
</bean>