Java 如何在 Spring Boot 中使用应用程序上下文获取 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34088780/
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-11 15:18:01  来源:igfitidea点击:

How to get bean using application context in spring boot

javaspringspring-bootdependency-injection

提问by Qasim

I am developing a SpringBoot project and I want to get the bean by its name using applicationContext. I have tried many solution from web but could not succeed. My Requirement is that I have a controller

我正在开发一个 SpringBoot 项目,我想使用applicationContext. 我从网上尝试了很多解决方案,但都没有成功。我的要求是我有一个控制器

ControllerA

and inside the controller I have a method getBean(String className). I want to get instance of registered bean. I have hibernate entities and I want to get an instance of the bean by passing the name of class only in getBeanmethod.

在控制器内部我有一个方法getBean(String className)。我想获取已注册 bean 的实例。我有休眠实体,我想通过仅在getBean方法中传递类的名称来获取 bean 的实例。

Please help if someone know the solution.

如果有人知道解决方案,请帮助。

回答by reos

You can Autowire the ApplicationContext, either as a field

您可以自动装配 ApplicationContext,或者作为一个字段

@Autowired
private ApplicationContext context;

or a method

或方法

@Autowired
public void context(ApplicationContext context) { this.context = context; }

Finally use

最后使用

context.getBean(SomeClass.class)

回答by luboskrnac

If you are inside of Spring bean (in this case @Controllerbean) you shouldn't use Spring context instance at all. Just autowire classNamebean directly.

如果您在 Spring bean(在本例中为@Controllerbean)内部,则根本不应使用 Spring 上下文实例。className直接自动装配bean。

BTW, avoid using field injection as it's considered as bad practice.

顺便说一句,避免使用字段注入,因为它被认为是不好的做法。

回答by Sundararaj Govindasamy

You can use ApplicationContextAware.

您可以使用ApplicationContextAware

ApplicationContextAware:

Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.

应用上下文感知

由任何希望被通知它运行的 ApplicationContext 的对象实现的接口。例如,当一个对象需要访问一组协作 bean 时,实现这个接口是有意义的。

There are a few methods for obtaining a reference to the application context. You can implement ApplicationContextAware as in the following example:

有几种方法可以获取对应用程序上下文的引用。您可以按照以下示例实现 ApplicationContextAware:

package hello;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    } 

 public ApplicationContext getContext() {
        return applicationContext;
    }

}

Update:

更新:

When Spring instantiates beans, it looks for ApplicationContextAwareimplementations, If they are found, the setApplicationContext() methods will be invoked.

Spring 实例化 beans 时,它会查找ApplicationContextAware实现,如果找到,将调用 setApplicationContext() 方法。

In this way, Spring is setting currentapplicationcontext.

通过这种方式,Spring 正在设置当前的应用程序上下文。

Code snippet from Spring's source code:

来自 Spring 的代码片段source code

private void invokeAwareInterfaces(Object bean) {
        .....
        .....
 if (bean instanceof ApplicationContextAware) {                
  ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext);
   }
}

Once you get the reference to Application context, you get fetch the bean whichever you want by using getBean().

一旦获得对应用程序上下文的引用,就可以使用 getBean() 获取所需的 bean。

回答by Debendra Parida

actually you want to get the object from the Spring engine, where the engine already maintaining the object of your required class at that starting of the spring application(Initialization of the Spring engine).Now the thing is you just have to get that object to a reference.

实际上,您想从 Spring 引擎获取对象,其中引擎已经在 Spring 应用程序启动时维护了所需类的对象(Spring 引擎的初始化)。现在,您只需要获取该对象即可一个参考。

in a service class

在服务类中

@Autowired
private ApplicationContext context;

SomeClass sc = (SomeClass)context.getBean(SomeClass.class);

now in the reference of the sc you are having the object. Hope explained well. If any doubt please let me know.

现在在您拥有对象的 sc 的参考中。希望解释得很好。如果有任何疑问,请告诉我。

回答by Ali Katkar

You can use ServiceLocatorFactoryBean. First you need to create an interface for your class

您可以使用 ServiceLocatorFactoryBean。首先你需要为你的类创建一个接口

public interface YourClassFactory {
    YourClass getClassByName(String name);
}

Then you have to create a config file for ServiceLocatorBean

然后你必须为 ServiceLocatorBean 创建一个配置文件

@Configuration
@Component
public class ServiceLocatorFactoryBeanConfig {

    @Bean
    public ServiceLocatorFactoryBean serviceLocatorBean(){
        ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
        bean.setServiceLocatorInterface(YourClassFactory.class);
        return bean;
    }
}

Now you can find your class by name like that

现在你可以通过这样的名字找到你的班级

@Autowired
private YourClassfactory factory;

YourClass getYourClass(String name){
    return factory.getClassByName(name);
}

回答by yeaaaahhhh..hamf hamf

You can use the ApplicationContextAware class that can provide the application context.

您可以使用可以提供应用程序上下文的 ApplicationContextAware 类。

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return ctx;
    }

    @Override
    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
        ApplicationContextProvider.ctx = ctx;
    }

    /**
     * Tries to autowire the specified instance of the class if one of the specified
     * beans which need to be autowired are null.
     *
     * @param classToAutowire        the instance of the class which holds @Autowire
     *                               annotations
     * @param beansToAutowireInClass the beans which have the @Autowire annotation
     *                               in the specified {#classToAutowire}
     */
    public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
        for (Object bean : beansToAutowireInClass) {
            if (bean == null) {
                ctx.getAutowireCapableBeanFactory().autowireBean(classToAutowire);
            }
        }
    }

}

回答by Sam

Just use:

只需使用:

org.springframework.beans.factory.BeanFactory#getBean(java.lang.Class)

org.springframework.beans.factory.BeanFactory#getBean(java.lang.Class)

Example:

例子:

@Component
public class Example {

    @Autowired
    private ApplicationContext context;

    public MyService getMyServiceBean() {
        return context.getBean(MyService.class);
    }

    // your code uses getMyServiceBean()
}