【发布时间】:2021-11-02 00:37:00
【问题描述】:
我正在开发一个 Spring Boot 应用程序。我的代码如下
@Slf4j
@RestController
public class TestController {
@Autowired
private TestService testService;
@Autowired
private TestConfig testConfig;
@GetMapping("testService")
public void testService() {
testService.printConfigValue();
}
@GetMapping("updateConfig/{value}")
public void updateConfig(String value) {
testConfig.setValue(value);
}
@GetMapping("testConfig")
public void testConfig() {
log.info("INSIDE CONTROLLER - Config value = {}", testConfig.getValue());
}
}
@Data
@Configuration
public class TestConfig {
private String value;
}
@Slf4j
@Service
public class TestService {
@Autowired
private TestConfig testConfig;
public void printConfigValue() {
log.info("INSIDE SERVICE - Config value = {}", testConfig.getValue());
}
}
当我使用 @GetMapping("updateConfig/{value}") 端点时说,值为 hello 并调用 testService 和 testConfig 端点时,我收到一个空值。如果我理解正确,Spring 应该默认将其 bean 视为单例。因此,如果我更新“updateConfig/{value}”端点中的 Autowired 配置,它应该在点击 @GetMapping("testService") 和 @GetMapping("testConfig") 端点时显示更新的值。但是我得到了 TestConfig 类的“值”字段的空值。有人可以解释一下吗?我在这里错过了什么?
【问题讨论】:
-
除其他外,我没有看到任何线程间同步正在进行。尝试使您的
value变量volatile。 -
仍然获得
null值。
标签: java spring spring-boot singleton autowired