justAnotherDev
justAnotherDev

Reputation: 283

Spring beans not being updated

I'm working on a Spring boot application. My code is as follows

@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());
    }
    
}

When I use the @GetMapping("updateConfig/{value}") endpoint say with a value of hello and call the testService & testConfig endpoints I'm receiving a null value. If I understand it correctly, Spring should treat its beans as singleton by default. So, if I update the Autowired config in the "updateConfig/{value}" endpoint it should show the updated value when hitting both @GetMapping("testService") & @GetMapping("testConfig") endpoints. But I'm getting a null value for the "value" field of TestConfig class. Can someone explain this? What am I missing here?

Upvotes: 1

Views: 512

Answers (1)

ray
ray

Reputation: 1670

You need to add @PathVariable annotation

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

Upvotes: 3

Related Questions