简体   繁体   English

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

[英]Spring JavaConfig: Retrieving beans by calling Configuration class/bean “directly”

I am wondering if this will get me into trouble or if it is a bad idea: 我想知道这是否会给我带来麻烦,还是一个坏主意:

@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();
    }
}

You may wonder why I would do as above and not: 您可能想知道为什么我会这样做而不是:

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();
    }
}

I do not like the second method as much, as it does not catch as many errors at compile-time. 我不太喜欢第二种方法,因为它在编译时没有捕获到太多错误。 For example if I do ctx.getBean(SomeNonBean.class) I would not get compile-time errors. 例如,如果我执行ctx.getBean(SomeNonBean.class),则不会出现编译时错误。 Also if someBean1() were private, the compiler would catch the error. 同样,如果someBean1()是私有的,则编译器将捕获该错误。

The preferred method would be to have 首选方法是

@Autowired
private SomeBean1 somebean1;

@Autowired
private SomeBean2 somebean2;

This is even cleaner, makes testing simpler, and avoids issues such as unnecessarily instantiating more copies than necessary. 这甚至更干净,使测试更简单,并且避免了诸如不必要地实例化多余副本的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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