Spring JavaConfig:通过直接调用Configuration class / bean来检索bean

时间:2013-08-02 21:56:41

标签: java spring

我想知道这是否会让我遇到麻烦或是否是一个坏主意:

@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()是私有的,编译器将捕获错误。

1 个答案:

答案 0 :(得分:0)

首选方法是

@Autowired
private SomeBean1 somebean1;

@Autowired
private SomeBean2 somebean2;

这甚至更清晰,使测试更简单,并避免诸如不必要地实例化更多副本之类的问题。

相关问题