Why is Spring's ApplicationContext.getBean considered bad?

前端 未结 14 2011
一整个雨季
一整个雨季 2020-11-22 14:33

I asked a general Spring question: Auto-cast Spring Beans and had multiple people respond that calling Spring\'s ApplicationContext.getBean() should be avoided

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:14

    It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:

    public class AutowireThisDriver {
    
        private MySpringBean mySpringBean;    
    
        public static void main(String[] args) {
           AutowireThisDriver atd = new AutowireThisDriver(); //get instance
    
           ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                      "/WEB-INF/applicationContext.xml"); //get Spring context 
    
           //the magic: auto-wire the instance with all its dependencies:
           ctx.getAutowireCapableBeanFactory().autowireBeanProperties(atd,
                      AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        
    
           // code that uses mySpringBean ...
           mySpringBean.doStuff() // no need to instantiate - thanks to Spring
        }
    
        public void setMySpringBean(MySpringBean bean) {
           this.mySpringBean = bean;    
        }
    }
    

    I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.

提交回复
热议问题