0
檢索豆我想知道如果這將讓我陷入麻煩,或者如果它是一個壞主意:春季JavaConfig:由「直接」呼叫配置類/豆
@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()是私有的,編譯器會捕獲錯誤。