简体   繁体   中英

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. Also if someBean1() were private, the compiler would catch the error.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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