繁体   English   中英

Spring JavaConfig:通过“直接”调用Configuration类/ bean来检索bean

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM