Spring get current ApplicationContext

后端 未结 11 929
陌清茗
陌清茗 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:57

    Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

    @Component
    public class SpringContext implements ApplicationContextAware{
    
       private static ApplicationContext applicationContext;
    
       @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws 
         BeansException {
        this.applicationContext=applicationContext;
       }
     }
    

    you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:

        applicationContext.getBean(String serviceName,Interface.Class)
    

提交回复
热议问题