Java Spring 获取当前的 ApplicationContext

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21827548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:55:56  来源:igfitidea点击:

Spring get current ApplicationContext

javaspringspring-mvcservlets

提问by LynAs

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

我正在为我的 Web 应用程序使用 Spring MVC。我的豆子写在“ spring-servlet.xml”文件中

Now I have a class MyClassand i want to access this class using spring bean

现在我有一个类MyClass,我想使用 spring bean 访问这个类

In the spring-servlet.xmli have written following

spring-servlet.xml我写的以下

<bean id="myClass" class="com.lynas.MyClass" />

Now i need to access this using ApplicationContext

现在我需要使用 ApplicationContext

ApplicationContext context = ??

So that I can do

这样我才能做到

MyClass myClass = (MyClass) context.getBean("myClass");

How to do this??

这该怎么做??

采纳答案by gipinani

Simply inject it..

只需注入它..

@Autowired
private ApplicationContext appContext;

or implement this interface: ApplicationContextAware

或实现此接口:ApplicationContextAware

回答by Hitesh Kumar

Add this to your code

将此添加到您的代码中

@Autowired
private ApplicationContext _applicationContext;

//Add below line in your calling method
MyClass class = (MyClass) _applicationContext.getBean("myClass");

// Or you can simply use this, put the below code in your controller data member declaration part.
@Autowired
private MyClass myClass;

This will simply inject myClass into your application

这将简单地将 myClass 注入您的应用程序

回答by PraZ

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

然后你可以检索bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org

参考:springbyexample.org

回答by Kamlesh Paunikar

Step 1:Inject following code in class

第一步:在类中注入以下代码

@Autowired
private ApplicationContext _applicationContext;

Step 2: Write Getter & Setter

第 2 步:编写 Getter 和 Setter

Step 3: define autowire="byType" in xml file in which bean is defined

第 3 步:在定义 bean 的 xml 文件中定义 autowire="byType"

回答by Vivek

I think this linkdemonstrates 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

我认为此链接演示了在任何地方获取应用程序上下文的最佳方法,即使在非 bean 类中也是如此。我觉得它非常有用。希望你也一样。下面是它的抽象代码

Create a new class ApplicationContextProvider.java

创建一个新类 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

在 application-context.xml 中添加一个条目

<bean id="applicationContextProvider"
                        class="com.java2novice.spring.ApplicationContextProvider"/>

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

在注释情况下(而不是 application-context.xml)

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

Get the context like this

获取这样的上下文

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

Cheers!!

干杯!!

回答by Jaroslav Záruba

In case you need to access the context from within a HttpServlet which itself is not instantiated by Spring(and therefore neither @Autowire nor ApplicationContextAware will work)...

如果您需要从自身未由 Spring 实例化HttpServlet 中访问上下文(因此 @Autowire 和 ApplicationContextAware 都不起作用)...

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

or

或者

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);


As for some of the other replies, think twice before you do this:

至于其他一些回复,请在执行此操作之前三思:

new ClassPathXmlApplicationContext("..."); // are you sure?

...as this does not give you the current context, rather it creates another instance of it for you. Which means 1) significant chunk of memory and 2) beans are not shared among these two application contexts.

...因为这不会为您提供当前上下文,而是为您创建了另一个实例。这意味着 1) 大量内存和 2) bean 在这两个应用程序上下文之间不共享。

回答by vsingh

Another way is to inject applicationContext through servlet.

另一种方式是通过servlet注入applicationContext。

This is an example of how to inject dependencies when using Spring web services.

这是使用 Spring Web 服务时如何注入依赖项的示例。

<servlet>
        <servlet-name>my-soap-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:my-applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>5</load-on-startup>

</servlet>

Alternate way is to add application Context in your web.xml as shown below

另一种方法是在 web.xml 中添加应用程序上下文,如下所示

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/classes/my-another-applicationContext.xml
        classpath:my-second-context.xml
    </param-value>
</context-param>

Basically you are trying to tell servlet that it should look for beans defined in these context files.

基本上,您试图告诉 servlet 它应该查找在这些上下文文件中定义的 bean。

回答by Juan

based on Vivek's answer, but I think the following would be better:

基于 Vivek 的回答,但我认为以下内容会更好:

@Component("applicationContextProvider")
public class ApplicationContextProvider implements ApplicationContextAware {

    private static class AplicationContextHolder{

        private static final InnerContextResource CONTEXT_PROV = new InnerContextResource();

        private AplicationContextHolder() {
            super();
        }
    }

    private static final class InnerContextResource {

        private ApplicationContext context;

        private InnerContextResource(){
            super();
        }

        private void setContext(ApplicationContext context){
            this.context = context;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return AplicationContextHolder.CONTEXT_PROV.context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac) {
        AplicationContextHolder.CONTEXT_PROV.setContext(ac);
    }
}

Writing from an instance method to a static field is a bad practice and dangerous if multiple instances are being manipulated.

如果操作多个实例,从实例方法写入静态字段是一种不好的做法并且很危险。

回答by rzymek

If you're implementing a class that's not instantiated by Spring, like a JsonDeserializer you can use:

如果你正在实现一个没有被 Spring 实例化的类,比如一个 JsonDeserializer,你可以使用:

WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
MyClass myBean = context.getBean(MyClass.class);

回答by Md. Sajedul Karim

There are many way to get application context in Spring application. Those are given bellow:

在 Spring 应用程序中有多种获取应用程序上下文的方法。这些是在下面给出的:

  1. Via ApplicationContextAware:

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class AppContextProvider implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    }
    
  1. 通过 ApplicationContextAware

    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    
    public class AppContextProvider implements ApplicationContextAware {
    
    private ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    }
    

Here setApplicationContext(ApplicationContext applicationContext)method you will get the applicationContext

这里setApplicationContext(ApplicationContext applicationContext)方法你会得到applicationContext

  1. Via Autowired:

    @Autowired
    private ApplicationContext applicationContext;
    
  1. 通过自动连线

    @Autowired
    private ApplicationContext applicationContext;
    

Here @Autowiredkeyword will provide the applicationContext.

这里@Autowired关键字将提供applicationContext。

For more info visit this thread

有关更多信息,请访问此线程

Thanks :)

谢谢 :)