从ImportBeanDefinitionRegistrar中的外部包配置类检索bean

时间:2019-01-25 15:30:26

标签: spring spring-boot

我正在尝试检索ImportBeanDefinitionRegistrar中不同包中定义的bean。

因此,例如,不同包中的bean被定义为:

package com.differentpackage

@Configuration
@ConditionalOnProperty(name = "app.some-property", havingValue = "true")
public class ExternalConfiguration {
    private ExampleProperties exampleProperties;

    public ExternalConfiguration(ExampleProperties exampleProperties) {
        this.exampleProperties = exampleProperties;
    }

    @Bean(destroyMethod = "destroy")
    public ExampleBean exampleBean()  {
        return new ExampleBean();
    }

    // other beans
    // ...
}

我想在我的ExampleBean中找到ImportBeanDefinitionRegistrar

package com.example

class MyRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        // Will result in a NoSuchBeanDefinitionException exception.
        ExampleBean exampleBean = ((DefaultListableBeanFactory) registry).getBean(ExampleBean.class);
    }
}

我将如何在我的注册商中检索该bean?

1 个答案:

答案 0 :(得分:0)

默认情况下,Spring仅从软件包和@SpringBootApplication所在的所有子软件包中扫描。您可以在scanBasePackages中配置@SpringBootConfiguration来更改扫描软件包:

@SpringBootApplication(scanBasePackages= {"com.differentpackage" ,"com.example" })

还要确保application.properties确实定义了app.some-property=true以便启用ExternalConfiguration