askstackoverflow
askstackoverflow

Reputation: 301

@Value from application.properties in SpringBoot gives null all the time

How to properly inject value from application.properties file?

main class:

@SpringBootApplication
public class Main {


    public static void main(String args[]) {
        SpringApplication.run(Main.class,args);
    }

application.properties file:

my.password=admin

test class:

@Component
public class Test {
    @Value("${my.password}")
    private String mypassword;

    public String getMypassword() {
        return mypassword;
    }

    public void setMypassword(String mypassword) {
        this.mypassword = mypassword;
    }

    public Test(){
        System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
    }
}

Console prints always null, not the value from application file

Upvotes: 0

Views: 940

Answers (2)

askstackoverflow
askstackoverflow

Reputation: 301

@pvpkiran I am trying to add this to my main method, rest is unchanged.

@SpringBootApplication
public class Application {
    @Autowired
    static Test  t;
    public static void main(String args[]){
        SpringApplication.run(Application.class,args);

        t.foobar();
    }
}

Upvotes: 0

pvpkiran
pvpkiran

Reputation: 27048

Properties are not injected when the class is being created (i.e when your constructor is called), but a bit later. Hence you see null in the constructor.

Try adding a method annotated with @PostConstruct like this and check the result:

@PostConstruct
public void afterCreation(){
    System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
}

Upvotes: 2

Related Questions