end*_*ess 3 java spring properties
我正在尝试以编程方式创建 AnnotationConfigApplicationContext。我在 Spring XML 文件中得到一个配置类列表和一个属性文件列表。
使用该文件,我可以使用 XmlBeanDefinitionReader 并加载所有 @Configuration 定义。但是,我无法加载属性。
这就是我正在做的加载属性..
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
for (String propFile : propertyFiles) {
propReader.loadBeanDefinitions(new ClassPathResource(propFile));
}
Run Code Online (Sandbox Code Playgroud)
代码只是在没有任何问题的情况下运行,但是一旦我调用 ctx.refresh() - 它会引发异常
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)
Run Code Online (Sandbox Code Playgroud)
所有类都在类路径上可用,如果我只是不以编程方式加载上述属性,应用程序就会正常运行(因为我使用其他方式加载属性)。
不确定,我在这里做错了什么。有任何想法吗?谢谢。
我不确定您为什么要手动加载属性,但是 AnnotationConfigApplicationContext 的 Spring 标准是
@Configuration
@PropertySource({"/props1.properties", "/props2.properties"})
public class Test {
...
Run Code Online (Sandbox Code Playgroud)
至于程序加载,使用 PropertySourcesPlaceholderConfigurer 而不是 PropertiesBeanDefinitionReader,这个例子工作正常
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
印刷
val1
Run Code Online (Sandbox Code Playgroud)