I have a very simple SpringBoot application where I defined a test component
package com.example.SpringBootDB_H2.model;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class TestCompnent {
@Value("${collateral.username}")
private String username;
public TestCompnent(){
log.info("Username : {}",username);
}
public TestCompnent(String username){
this.username = username;
}
}
in "application.yml" I have :
collateral:
username: ABCD
but on the startup it prints:
.e.SpringBootDB_H2.model.TestCompnent : Username : null
why?
I think it's about Spring Bean's life cycle issue.
Property values are injected after the constructor is called, so, normally, username is null. So, if you want to check whether the property you've set is appropriate, you can check it at @PostConstruct
, rather than in the constructor.
package com.example.SpringBootDB_H2.model;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@Slf4j
public class TestCompnent {
@Value("${collateral.username}")
private String username;
public TestCompnent() {
// Constructor is empty, injection hasn't happened yet
}
public TestCompnent(String username) {
this.username = username;
}
// here
@PostConstruct
private void init() {
log.info("Username : {}", username);
}
}