简体   繁体   English

Spring未在JavaConfig中拾取的Bean上的@PropertySource

[英]@PropertySource on a bean not picked up by Spring in JavaConfig

I've got 2 different maven projects: project A and project B, where A is a maven dependency of B. Project A has a class annotated with @PropertySource : 我有2个不同的Maven项目:项目A和项目B,其中A是B的Maven依赖项。项目A的类带有@PropertySource注释:

@Component
@PropertySource({"classpath:spring-files/resource.properties"})
public class BeanAImpl implements BeanA{

@Value("#{\'${list.of.some.properties}\'.split(\',\')}")
    private String someProperties;
}

In project B, I want to be able to define BeanAImpl. 在项目B中,我希望能够定义BeanAImpl。 So I define it in my JavaConfig class of project B: 因此,我在项目B的JavaConfig类中定义了它:

@Configuration
public class ProjectBConfig{

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

I get a BeanCreationException, since the injection of the List into "someProperties" has failed. 我收到BeanCreationException,因为将List注入“ someProperties”失败。 If I add to my @Configuration class (in project B) a component scan annotation for BeanAImpl's package, then the context will load successfully. 如果在我的@Configuration类中(在项目B中)为BeanAImpl的程序包添加了组件扫描注释,则上下文将成功加载。 Also, if I add the @PropertySource declaration to the config class - then it's going to work. 另外,如果我将@PropertySource声明添加到config类中,那么它将起作用。 But it seems that simply defining beanA in the configuration, does not take into account its annotations. 但是似乎仅在配置中定义beanA并没有考虑其注释。 I also tried changing beanA from @Component to @Configuration , which did not help. 我还尝试将beanA从@Component更改为@Configuration ,但没有帮助。

Is there a way for me to have BeanAImpl inject the value from the properties by simply defining it as a bean, without needing to add extra configuration? 我是否可以通过简单地将BeanAImpl定义为Bean来从属性中注入值,而无需添加额外的配置? Why is this happening? 为什么会这样呢?

@PropertySource annotation should be on class annotated with @Configuration , something similar to this: @PropertySource批注应在使用@Configuration批注的类上,类似于以下内容:

@Configuration
@PropertySource({"classpath:spring-files/resource.properties"})
public class ProjectBConfig{

Or you can create separate configuration class in project A. 或者,您可以在项目A中创建单独的配置类。

See javadoc for details of @PropertySource annotation. 有关@PropertySource批注的详细信息,请参见javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM