[英]Spring JavaConfig: Retrieving beans by calling Configuration class/bean “directly”
我想知道這是否會給我帶來麻煩,還是一個壞主意:
@Configuration
public class MyConfig {
@Bean
public SomeBean1 someBean1() {
return ...
}
@Bean
public SomeBean2 someBean2() {
return ...
}
}
public class Main {
public static void main(String[] args) throws Throwable {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HubBrokerConfig.class);
MyConfig conf = ctx.getBean(MyConfig.class);
conf.someBean1().doSomething();
conf.someBean2().doSomething();
}
}
您可能想知道為什么我會這樣做而不是:
public class Main {
public static void main(String[] args) throws Throwable {
ApplicationContext ctx = new AnnotationConfigApplicationContext(HubBrokerConfig.class);
ctx.getBean(SomeBean1.class)).doSomething();
ctx.getBean(SomeBean2.class)).doSomething();
}
}
我不太喜歡第二種方法,因為它在編譯時沒有捕獲到太多錯誤。 例如,如果我執行ctx.getBean(SomeNonBean.class),則不會出現編譯時錯誤。 同樣,如果someBean1()是私有的,則編譯器將捕獲該錯誤。
首選方法是
@Autowired
private SomeBean1 somebean1;
@Autowired
private SomeBean2 somebean2;
這甚至更干凈,使測試更簡單,並且避免了諸如不必要地實例化多余副本的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.