如果您已经在使用@Configuration 来配置 bean,为什么不使用构造函数注入?
我建议你重写A类如下:
public class A {
private final Supplier<Set<String>> sup;
public A(Supplier<Set<String>> sup) {
this.sup = sup;
}
}
现在您可以使用以下选项之一:
@Configuration
public class SampleConfig {
@Bean
public Supplier<Set<String>> set () {
return () -> Set.of("a","b", "c");
}
@Bean
public A a (Supplier<Set<String>> sup) {
return new A(sup);
}
}
或者其他方式:
@Configuration
public class SampleConfig {
@Bean
public Supplier<Set<String>> set () {
return () -> Set.of("a","b", "c");
}
@Bean
public A a () {
return new A(set());
}
}
在第二个选项中,我将set() 称为常规方法。 Spring 处理带有@Configuration 注释的类,因此它是用于注入的“特殊”调用。
由于供应商是单例,因此多次调用此 set 方法(例如,来自不同的 bean)将返回供应商的相同实例。
第一种方法更灵活,因为它允许将供应商和 A 类的定义保存在不同的配置文件中,第二种方法假设它们都定义在同一个 @Configuration 中。
更新(基于 Op 的评论)
使用字段注入,它的工作原理是一样的:
public class A {
@Autowired
private Supplier<Set<String>> sup;
public Set<String> getSet() {
return this.sup.get();
}
}
@Configuration
public class SampleConfig {
@Bean
public Supplier<Set<String>> set () {
return () -> Set.of("a","b", "c");
}
@Bean
public A a () {
return new A();
}
// this is called right before the application gets started (after all the injections are done - this is just for the sake of illustration)
@EventListener(ApplicationReadyEvent.class)
public void onReady(ApplicationReadyEvent evt) {
A a = evt.getApplicationContext().getBean(A.class);
System.out.println(a.getSet()); // this will return your set
}
}