endless
endless

Reputation: 3473

Loading properties in Spring 3.1 programmatically

I am trying to create a AnnotationConfigApplicationContext programmatically. I am getting a list of Configuration classes and a list of property files to go with it in a Spring XML file.

Using that file, I am able to use XmlBeanDefinitionReader and load all @Configuration definitions fine. But, I am not able to load properties.

This is what I am doing to load properties..

PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
for (String propFile : propertyFiles) {
    propReader.loadBeanDefinitions(new ClassPathResource(propFile));
}

Code just runs through this without any issues, but once I call ctx.refresh() -- it throws an exception

Caused by: java.lang.IllegalStateException: No bean class specified on bean definition
        at org.springframework.beans.factory.support.AbstractBeanDefinition.getBeanClass(AbstractBeanDefinition.java:381)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:54)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)

All the classes are available on the classpath, if I just don't load the above properties programmatically application just comes up fine (Because I am using other way to load properties).

Not sure, what I am doing wrong here. Any ideas? Thanks.

Upvotes: 3

Views: 12910

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

I am not sure why you are loading properties manually, but Spring standard for AnnotationConfigApplicationContext is

@Configuration
@PropertySource({"/props1.properties", "/props2.properties"})
public class Test {
...

as for programatic loading, use PropertySourcesPlaceholderConfigurer instead of PropertiesBeanDefinitionReader, this example works OK

@Configuration
public class Test {
    @Value("${prop1}")    //props1.properties contains prop1=val1 
    String prop1;

    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(Test.class);
        PropertySourcesPlaceholderConfigurer pph = new PropertySourcesPlaceholderConfigurer();
        pph.setLocation(new ClassPathResource("/props1.properties"));
        ctx.addBeanFactoryPostProcessor(pph);
        ctx.refresh();
        Test test = ctx.getBean(Test.class);
        System.out.println(test.prop1);
    }
}

prints

val1

Upvotes: 6

Related Questions