具有动态参数的Spring-Boot @Bean生产者

时间:2019-09-12 11:19:22

标签: java spring-boot dependency-injection qualifiers

我正在处理一组相似的Bean,只是在某些属性上有所不同,而我试图实现的是只有一个方法来生产这种Bean,但可以通过以下方式进行“配置”或自定义一些参数,可能带有自定义的@Qualifier批注。 这样的事情有可能吗?

例如,我想将此@Annotation用作自动装配不同@Bean的限定符:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface CustomQualifier {    
    int length();
    int height();
}

然后只有一种方法,通过读取注释的参数来生成不同的@Bean。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DynamicReportsConfiguration {

    @Bean
    @CustomQualifier // Here I do not want to set the fields' value
    public MyBean produceBean() {
        // TODO Read the fields of the @CustomQualifier
        int length;
        int height;

        return new MyBean(length, height);
    }
}

然后我只想指定注入点上的字段,例如:

@Autowired
@CustomQualifier(length=10, height=50)
private MyBean myBean;

如何实现这样的事情,而不必为高度和长度值的每种特定组合创建方法?

2 个答案:

答案 0 :(得分:0)

Spring不支持这样的事情。 实际上,spring使用反射来注入依赖项。 Spring引擎不知道您的自定义注释。

答案 1 :(得分:0)

我知道这不是您问题的直接答案。但是,作为一种解决方法,这应该可以工作。

@Configuration
public class DynamicReportsConfiguration {

    @Bean
    public BiFunction<Integer, Integer, MyBean> myBeanFactory() {
        return (l, h) -> produceBean(l, h); // or this::produceBean
    }

    @Bean
    public MyBean produceBean(int length, int height) {

        return new MyBean(length, height);
    }
}

我们可以像下面这样使用

@Autowired
private BiFunction<Integer, Integer, MyBean> myBeanFactory;


MyBean myBean = myBeanFactory.apply(length, height);