Loading properties in Spring 3.1 programmatically

风格不统一 提交于 2020-01-13 13:51:53

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/14167332/loading-properties-in-spring-3-1-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!