Spring get current ApplicationContext

后端 未结 11 930
陌清茗
陌清茗 2020-11-28 20:04

I am using Spring MVC for my web application. My beans are written in \"spring-servlet.xml\" file

Now I have a class MyClass and i want to

11条回答
  •  悲哀的现实
    2020-11-28 20:46

    I think this link demonstrates the best way to get application context anywhere, even in the non-bean class. I find it very useful. Hope its the same for you. The below is the abstract code of it

    Create a new class ApplicationContextProvider.java

    package com.java2novice.spring;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class ApplicationContextProvider implements ApplicationContextAware{
    
        private static ApplicationContext context;
    
        public static ApplicationContext getApplicationContext() {
            return context;
        }
    
        @Override
        public void setApplicationContext(ApplicationContext ac)
                throws BeansException {
            context = ac;
        }
    }
    

    Add an entry in application-context.xml

    
    

    In annotations case (instead of application-context.xml)

    @Component
    public class ApplicationContextProvider implements ApplicationContextAware{
    ...
    }
    

    Get the context like this

    TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);
    

    Cheers!!

提交回复
热议问题