【问题标题】:Spring beans not being updatedSpring bean 未更新
【发布时间】: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


【解决方案1】:

需要添加@PathVariable注解

@GetMapping("updateConfig/{value}")
public void updateConfig(@PathVariable("value") String value) {
    testConfig.setValue(value);
}

【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2021-02-13
    • 1970-01-01
    • 2011-09-07
    • 2012-02-04
    • 1970-01-01
    • 2023-03-23
    • 2012-07-22
    • 2012-11-15
    相关资源
    最近更新 更多