在 Spring Boot 中通过 @Value 检索 application.properties 值
Retrieve application.properties values via @Value in SpringBoot
我正在尝试从 application.properties 文件中提取数据 Spring Boot
application.properties
host=localhost:8080
accountNumber=1234567890
TestController.java
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testServiceImpl;
@Value("${host}")
private String host;
@RequestMapping("/test")
public String test() {
testServiceImpl = new TestService();
return testServiceImpl.getValue();
}
TestServiceImpl.java
@Service
public class TestServiceImpl implements TestService{
@Value("${accountNumber}")
public String value;
public String getValue(){
return value;
}
当我对 localhost:8080/test 进行 REST 调用时,我得到一个空值。
TestServiceImpl
已实例化,但 @Value
似乎不起作用。
我错过了什么吗?
解决方案:
我所要做的就是删除行 testServiceImpl = new TestService();
我假设它这样做是因为 new TestService()
正在覆盖 TestService
的自动装配实例
待更新:
Spring通过@Autowired实现的DI annotation.It为我们创建对象
@Autowired
private TestService testServiceImpl;
.
.
.
@RequestMapping("/test")
public String test() {
// testServiceImpl = new TestService(); // make comment this line
return testServiceImpl.getValue();
}
我找到的解决方案非常简单。
我所要做的就是删除行 testServiceImpl = new TestService();
我假设它这样做是因为 new TestService() 正在覆盖 TestService 的自动装配实例。
感谢 harsavmb 验证我的解决方案。
希望这对许多 Spring 新手有帮助 :)
我正在尝试从 application.properties 文件中提取数据 Spring Boot
application.properties
host=localhost:8080
accountNumber=1234567890
TestController.java
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private TestService testServiceImpl;
@Value("${host}")
private String host;
@RequestMapping("/test")
public String test() {
testServiceImpl = new TestService();
return testServiceImpl.getValue();
}
TestServiceImpl.java
@Service
public class TestServiceImpl implements TestService{
@Value("${accountNumber}")
public String value;
public String getValue(){
return value;
}
当我对 localhost:8080/test 进行 REST 调用时,我得到一个空值。
TestServiceImpl
已实例化,但 @Value
似乎不起作用。
我错过了什么吗?
解决方案:
我所要做的就是删除行 testServiceImpl = new TestService();
我假设它这样做是因为 new TestService()
正在覆盖 TestService
待更新:
Spring通过@Autowired实现的DI annotation.It为我们创建对象
@Autowired
private TestService testServiceImpl;
.
.
.
@RequestMapping("/test")
public String test() {
// testServiceImpl = new TestService(); // make comment this line
return testServiceImpl.getValue();
}
我找到的解决方案非常简单。
我所要做的就是删除行 testServiceImpl = new TestService();
我假设它这样做是因为 new TestService() 正在覆盖 TestService 的自动装配实例。
感谢 harsavmb 验证我的解决方案。
希望这对许多 Spring 新手有帮助 :)