2013-08-02 88 views
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()是私有的,編譯器會捕獲錯誤。

回答

0

的優選方法是將有

@Autowired 
private SomeBean1 somebean1; 

@Autowired 
private SomeBean2 somebean2; 

這是更清潔,使測試更簡單,並且避免了諸如不必要地超過需要實例化多個拷貝的問題。