我正在处理一组相似的 Bean,只是在某些属性上有所不同,我想要实现的是只有一个方法来生成这样的 Bean,但可以通过“配置”或自定义一些参数,可能带有自定义 @Qualifier 注释。 这样的事情可能吗?
例如,我想使用这个@Annotation 作为 Autowiring 不同@Beans 的限定符:
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();
}
然后只有一个方法可以通过读取注释的参数来生成不同的@Beans。
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);
}
}
然后我只想指定注入(inject)点上的字段,例如:
@Autowired
@CustomQualifier(length=10, height=50)
private MyBean myBean;
我怎样才能实现这样的目标,而不必为每个特定的高度和长度值组合创建一个方法?
最佳答案
Spring不支持这样的东西。 其实spring是用反射来注入(inject)依赖的。 spring 引擎不知道你的自定义注解。
关于java - 具有动态参数的 Spring-Boot @Bean 生产者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905578/