1ac0
1ac0

Reputation: 2939

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?

Upvotes: 0

Views: 1104

Answers (2)

CorayThan
CorayThan

Reputation: 17825

You need to access the property from a Spring bean, and you need to properly wire in the properties. First, add to your config class this:

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {

    PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
    props.setLocations(new Resource[] { new ClassPathResource("com/ektyn/springProperties/nejake.properties") }); //I think that's its absolute location, but you may need to play around with it to make sure
    return props;
}

Then you need to access them from within a Spring Bean. Typically, your config file should not be a bean, so I would recommend you make a separate class, something like this:

@Component //this makes it a spring bean
public class PropertiesAccessor {

   @Value("${klucik}")
    private String klc;

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

Finally, add this to your config to make it find the PropertiesAccessor:

@ComponentScan("com.ektyn.springProperties")

Then you can access the PropertiesAccessor bean from your app context and call its printIt method.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

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");

Upvotes: 2

Related Questions