Spring通过ApplicationContext主动获取bean

有些场景无法通过AutoWired和compoment注解传递进来,于是希望通过Spring context主动去获取bean
demo:

package com.qhong.Util;

import org.springframework.context.ApplicationContext;

public class SpringUtil{

    private static ApplicationContext applicationContext = null;

    public static void setApplicationContext(ApplicationContext applicationContext){
        if(SpringUtil.applicationContext == null){
            SpringUtil.applicationContext  = applicationContext;
        }

    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);

    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

}

调用:

package com.qhong;

import com.qhong.Util.SpringUtil;
import com.qhong.Util.SpringUtilTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootDemoApplication  {
    public static void main(String[] args) {

        ApplicationContext ctx=    SpringApplication.run(SpringBootDemoApplication.class, args);
        SpringUtil.setApplicationContext(ctx);

        String[] beanNames =  ctx.getBeanDefinitionNames();
        System.out.println("beanNames个数:"+beanNames.length);
        for(String bn:beanNames){
            System.out.println(bn);
        }

        SpringUtilTest sut=SpringUtil.getBean(SpringUtilTest.class);
        sut.setAge(31);
        sut.setName("hongdada");
        sut.show();

    }
}

因为比较懒,就没有创建其他类,直接在main里面运行的。

output:

beanNames个数:177
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
springBootDemoApplication
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
mongodbLog
webLogAspect
springUtilTest
helloController
userController
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
propertySourcesPlaceholderConfigurer
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration
websocketContainerCustomizer
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
tomcatEmbeddedServletContainerFactory
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
embeddedServletContainerCustomizerBeanPostProcessor
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
dispatcherServlet
dispatcherServletRegistration
spring.mvc.CONFIGURATION_PROPERTIES
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
error
beanNameViewResolver
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration
errorAttributes
basicErrorController
errorPageCustomizer
preserveErrorControllerTargetClassPostProcessor
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration
requestMappingHandlerAdapter
requestMappingHandlerMapping
mvcContentNegotiationManager
viewControllerHandlerMapping
beanNameHandlerMapping
resourceHandlerMapping
mvcResourceUrlProvider
defaultServletHandlerMapping
mvcConversionService
mvcValidator
mvcPathMatcher
mvcUrlPathHelper
mvcUriComponentsContributor
httpRequestHandlerAdapter
simpleControllerHandlerAdapter
handlerExceptionResolver
mvcViewResolver
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
faviconHandlerMapping
faviconRequestHandler
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
defaultViewResolver
requestContextFilter
viewResolver
spring.resources.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
hiddenHttpMethodFilter
httpPutFormContentFilter
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
mbeanExporter
objectNamingStrategy
mbeanServer
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
springApplicationAdminRegistrar
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration
spring.jta.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration
jdbcTemplate
namedParameterJdbcTemplate
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration
dataSource
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfiguration
dataSourceInitializer
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration$TomcatDataSourcePoolMetadataProviderConfiguration
tomcatPoolDataSourceMetadataProvider
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.datasource.CONFIGURATION_PROPERTIES
dataSourceInitializerPostProcessor
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration
openEntityManagerInViewInterceptor
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
transactionManager
jpaVendorAdapter
entityManagerFactoryBuilder
entityManagerFactory
spring.jpa.CONFIGURATION_PROPERTIES
dataSourceInitializedPublisher
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration
persistenceExceptionTranslationPostProcessor
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor
emBeanDefinitionRegistrarPostProcessor
jpaMappingContext
jpaContext
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration
mongo
spring.data.mongodb.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
jacksonObjectMapperBuilder
spring.jackson.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
jacksonObjectMapper
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
stringHttpMessageConverter
spring.http.encoding.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
mappingJackson2HttpMessageConverter
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration
messageConverters
org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration
pageableResolver
sortResolver
pagedResourcesAssembler
pagedResourcesAssemblerArgumentResolver
org.springframework.data.web.config.SpringDataJacksonConfiguration
jacksonGeoModule
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration$EntityLinksConfiguration
entityLinksPluginRegistry
controllerEntityLinks
delegatingEntityLinks
org.springframework.hateoas.config.HateoasConfiguration
linkRelationMessageSource
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration$HypermediaConfiguration
halObjectMapperConfigurer
_halObjectMapper
org.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$DefaultObjectMapperCustomizer#0
org.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$Jackson2ModuleRegisteringBeanPostProcessor#0
_linkDiscovererRegistry
org.springframework.hateoas.LinkDiscoverers#0
defaultRelProvider
annotationRelProvider
relProviderPluginRegistry
_relProvider
org.springframework.boot.autoconfigure.hateoas.HypermediaHttpMessageConverterConfiguration
halMessageConverterSupportedMediaTypeCustomizer
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration
spring.hateoas.CONFIGURATION_PROPERTIES
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
transactionAttributeSource
transactionInterceptor
org.springframework.transaction.config.internalTransactionalEventListenerFactory
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$TransactionManagementConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
transactionTemplate
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration
characterEncodingFilter
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration
multipartConfigElement
multipartResolver
multipart.CONFIGURATION_PROPERTIES
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
serverProperties
duplicateServerPropertiesDetector
org.springframework.orm.jpa.SharedEntityManagerCreator#0
SpringUtilTest(name=hongdada, age=31)

http://blog.csdn.net/jinzhencs/article/details/51673782

http://blog.csdn.net/silyvin/article/details/70832415

http://blog.csdn.net/u014695188/article/details/52396880

http://timerbin.iteye.com/blog/2252886

原文地址:https://www.cnblogs.com/hongdada/p/8196536.html

时间: 2024-10-18 12:03:57

Spring通过ApplicationContext主动获取bean的相关文章

Spring在代码中获取bean的几种方式(转:http://www.dexcoder.com/selfly/article/326)

方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObjectSupport 方法四:继承自抽象类WebApplicationObjectSupport 方法五:实现接口ApplicationContextAware 方法六:通过Spring提供的ContextLoader 获取spring中bean的方式总结: 方法一:在初始化时保存Applicati

Spring在代码中获取bean的几种方式

方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObjectSupport 方法四:继承自抽象类WebApplicationObjectSupport 方法五:实现接口ApplicationContextAware 方法六:通过Spring提供的ContextLoader 获取spring中bean的方式总结: 方法一:在初始化时保存Applicati

Spring初始化ApplicationContext为null

1. ApplicationContextAware初始化 通过它Spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法. 我们在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean. 使用方法如下: 1.实现ApplicationContextAware接口: package com.bis.majian.practice.module.sp

[原创]java WEB学习笔记98:Spring学习---Spring Bean配置及相关细节:如何在配置bean,Spring容器(BeanFactory,ApplicationContext),如何获取bean,属性赋值(属性注入,构造器注入),配置bean细节(字面值,包含特殊字符,引用bean,null值,集合属性list map propert),util 和p 命名空间

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

手动获取spring的ApplicationContext和bean对象

WEB项目: 方法1: 1 ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc) 方法2: 1 ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc) 方法3: 1 写一个工具类类继承ApplicationOb

spring 的 ApplicationContext.getBean(type) 无法获取bean,报错

具体问题请看   https://q.cnblogs.com/q/108101/ 研究了两天: 经过上文中的排除法: 造成问题的原因是要获取的bean 中 有被切入的方法.. 就是可能该类会使用反射生成一个类.. 怎么测试呢? 想到 @Autowired  和 @Resource  这两个注解.. 他们会通过 类型 和 名称去找容器中对应 的 bean .. 于是在controller 中使用 这个注解 注入 zaService; 报错了  : Caused by: org.springfram

怎么获取Spring的ApplicationContext

在 WEB 开发中,可能会很少需要显示的获得 ApplicationContext 来得到由 Spring 进行管理的某些 Bean, 今天我就遇到了,在这里和大家分享一下, WEB 开发中,怎么获取 ApplicationContext 一       要想怎么获取 ApplicationContext, 首先必须明白 Spring 内部 ApplicationContext 是怎样存储的.下面我们来跟踪一下源码 首先:从大家最熟悉的地方开始 Java代码   <listener> <

spring 获取 bean

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext()); TopicAction result = (TopicAction)ac1.getBean("TopicAction"); spring 获取 bean

Web开发中获取Spring的ApplicationContext的三种方式

在 WEB 开发中,可能会很少需要显示的获得 ApplicationContext 来得到由 Spring 进行管理的某些 Bean, 今天我就遇到了,在这里和大家分享一下, WEB 开发中,怎么获取 ApplicationContext 一       要想怎么获取 ApplicationContext, 首先必须明白 Spring 内部 ApplicationContext 是怎样存储的.下面我们来跟踪一下源码 首先:从大家最熟悉的地方开始 Java代码   <listener> <