【发布时间】:2019-09-01 07:44:03
【问题描述】:
我正在学习 Spring Boot,我可能有非常简单的问题,但对我来说还不够清楚。我在使用 @Value 注释时遇到了一些问题——我想知道为什么 apprication 属性不能注入到类参数中。
我使用 Spring Initializr 准备了一些非常基本的项目,并在我的“application.properties”资源中添加了一个属性。此外,我创建了两个额外的类:“YellowCar”(工作正常)和“RedCar”(不起作用 - 无法正确注入参数)。
“application.properties”文件:
car.age=15
我的应用程序的主类:
package com.example.helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
@SpringBootApplication
public class HelperApplication implements CommandLineRunner {
@Autowired
private Environment env;
public static void main(String[] args) {
SpringApplication.run(HelperApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println (new RedCar(env));
System.out.println (new YellowCar());
}
}
RedCar 是通过将环境变量传递给构造函数来构建的:
package com.example.helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class RedCar {
private int age;
@Autowired
public RedCar (Environment env) {
this.age = new Integer(env.getRequiredProperty("car.age")).intValue();
}
@Override
public String toString() {
return "Car [age=" + age + "]";
}
}
YellowCar 是在没有将环境变量传递给构造函数的情况下构建的,而是使用 @Value 注释:
package com.example.helper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class YellowCar {
@Value("${car.age}")
private int age;
@Override
public String toString() {
return "YellowCar [age=" + age + "]";
}
}
这是程序输出:
Car [age=15]
YellowCar [age=0]
如您所见,YellowCar 的年龄未正确注入(等于 0)。
我的目标:我不想到处都将 Environment 对象传递给其他类的构造函数……我想改用 @Value annotatnio。有人可以解释一下吗: 1)为什么我的代码不起作用? 2) 应如何更新此代码以获得以下输出?
Car [age=15]
YellowCar [age=15]
谢谢!
【问题讨论】:
标签: spring properties annotations autowired application.properties