Search code examples
javaspring-annotations

Spring annotations, read properties


I have small test project to test Spring annotations:

enter image description here

where in nejake.properties is:

klucik = hodnoticka

and in App.java is:

@Configuration
@PropertySource("classpath:/com/ektyn/springProperties/nejake.properties")
public class App
{
    @Value("${klucik}")
    private String klc;



    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext();
        ctx1.register(App.class);
        ctx1.refresh();
        //
        App app = new App();
        app.printIt();
    }



    private void printIt()
    {
        System.out.println(klc);
    }
}

It should print hodnoticka on console, but prints null - String value is not initialized. My code is bad - at the moment I have no experience with annotation driven Spring. What's bad with code above?


Solution

  • You created the object yourself

    App app = new App();
    app.printIt();
    

    how is Spring supposed to manage the instance and inject the value?

    You will however need

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    

    to make the properties available. Also, because the App bean initialized for handling @Configuration is initialized before the resolver for @Value, the value field will not have been set. Instead, declare a different App bean and retrieve it

    @Bean
    public App appBean() {
        return new App();
    }
    ...
    App app = (App) ctx1.getBean("appBean");