简体   繁体   English

使已定义的spring bean为主要对象

[英]Making a defined spring bean primary

I have 3 beans of the same type defined in spring.xml. 我有3个在spring.xml中定义的相同类型的bean。 This is inside a jar file which I cannot edit. 这是我无法编辑的jar文件中。 I want to make one of these primary in my spring-boot application using annotation. 我想使用注解在我的spring-boot应用程序中使这些成为主要对象之一。 Is there a way to do it? 有办法吗?

A straightforward approach is to use a bridge configuration, which will register the desired bean as a new primary bean. 一种简单的方法是使用网桥配置,该配置会将所需的bean注册为新的主bean。 A simple example: 一个简单的例子:

The interface: 界面:

public interface Greeter { String greet(); }

The configuration which you don't control: 您无法控制的配置:

@Configuration
public class Config1 {
    @Bean public Greeter british(){ return () -> "Hi"; }
    @Bean public Greeter obiWan(){ return () -> "Hello there"; }
    @Bean public Greeter american(){ return () -> "Howdy"; }
}

The bridge configuration: 网桥配置:

@Configuration
public class Config2 {
    @Primary @Bean public Greeter primary(@Qualifier("obiWan") Greeter g) { 
        return g; 
    }
}

The client code: 客户端代码:

@RestController
public class ControllerImpl {
    @Autowired
    Greeter greeter;

    @RequestMapping(path = "/test", method = RequestMethod.GET)
    public String test() {
        return greeter.greet();
    }
}

Result of curl http://localhost:8080/test will be curl http://localhost:8080/test将是

Hello there

您可以使用@Qualifier("___beanName__")注释选择正确的注释

I tried @jihor solutions but it doesn't work. 我尝试了@jihor解决方案,但没有用。 I have a NullPointerException in defined configuration. 我在定义的配置中有一个NullPointerException

Then I find the next solution on Spring Boot 然后我在Spring Boot上找到下一个解决方案

@Configuration
public class Config1 {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.ddbb")
    public JndiPropertyHolder ddbbProperties() {
        return new JndiPropertyHolder();
    }

    @ConditionalOnProperty(name = "spring.datasource.ddbb.primary", matchIfMissing = false, havingValue = "true")
    @Bean("ddbbDataSource")
    @Primary
    public DataSource ddbbDataSourcePrimary() {
        return new JndiDataSourceLookup().getDataSource(ddbbProperties().getJndiName());
    }

    @ConditionalOnProperty(name = "spring.datasource.ddbb.primary", matchIfMissing = true, havingValue = "false")
    @Bean("ddbbDataSource")
    public DataSource ddbbDataSource() {
        return new JndiDataSourceLookup().getDataSource(ddbbProperties().getJndiName());
    }
}

And my application.properties if I need this datasource as primary, otherwise don't set the property or set false. 还有我的application.properties(如果我需要将此数据源作为主要数据源),否则请不要设置该属性或将其设置为false。

spring.datasource.ddbb.primary=true

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

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