根据属性占位符有条件地实例化一个spring bean

kga*_*ron 0 java spring

是否可以配置spring来实例化bean,具体取决于布尔占位符属性?或者至少从基于这样的属性的注释扫描中排除包?

gce*_*gce 10

您可以使用ConditionalOnProperty

@Bean
@ConditionalOnProperty(value = "property", havingValue = "value", matchIfMissing = true)
public MyBean myBean() ...
Run Code Online (Sandbox Code Playgroud)

另外,请检查这个答案。


Ayu*_*lik 6

我认为您应该使用Spring 配置文件来配置不同的行为.但是,如果使用注释,则可以创建@Configuration对象和工厂方法,以根据属性值创建bean

例如

@Configuration
class ExampleConfig {
    private final String prop;

    public ExampleConfig(@Value("${your.prop.name}" prop} {
       this.prop = prop;
    }

    @Bean 
    public YourBeanClass create() {
         if (prop.equals("someValue") {
            return new YourBeanClass();
         }
         return new OtherClass(); // must be subclass/implementation of YBC
    } 
}
Run Code Online (Sandbox Code Playgroud)


Oph*_*ian 1

这可能不符合您的需求,并且我假设您可以控制相关类(即不是供应商代码),但是您是否考虑过将 bean 标记为延迟加载?至少,这样它在实际使用之前不会被实例化,这可能会根据您的配置的其余部分有条件地发生。