Spring通過ApplicationContext主動擷取bean

來源:互聯網
上載者:User

標籤:jdb   ref   bind   basic   socket   gpo   mongod   ali   mapper   

有些情境無法通過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;@SpringBootApplicationpublic 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個數:177org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.annotation.internalPersistenceAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactoryspringBootDemoApplicationorg.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessororg.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessormongodbLogwebLogAspectspringUtilTesthelloControlleruserControllerorg.springframework.boot.autoconfigure.AutoConfigurationPackagesorg.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurationorg.springframework.boot.autoconfigure.condition.BeanTypeRegistrypropertySourcesPlaceholderConfigurerorg.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfigurationwebsocketContainerCustomizerorg.springframework.boot.autoconfigure.websocket.WebSocketAutoConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcattomcatEmbeddedServletContainerFactoryorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfigurationembeddedServletContainerCustomizerBeanPostProcessororg.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfigurationdispatcherServletdispatcherServletRegistrationspring.mvc.CONFIGURATION_PROPERTIESorg.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessororg.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.storeorg.springframework.boot.autoconfigure.web.DispatcherServletAutoConfigurationorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfigurationerrorbeanNameViewResolverorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfigurationerrorAttributesbasicErrorControllererrorPageCustomizerpreserveErrorControllerTargetClassPostProcessororg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfigurationrequestMappingHandlerAdapterrequestMappingHandlerMappingmvcContentNegotiationManagerviewControllerHandlerMappingbeanNameHandlerMappingresourceHandlerMappingmvcResourceUrlProviderdefaultServletHandlerMappingmvcConversionServicemvcValidatormvcPathMatchermvcUrlPathHelpermvcUriComponentsContributorhttpRequestHandlerAdaptersimpleControllerHandlerAdapterhandlerExceptionResolvermvcViewResolverorg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfigurationfaviconHandlerMappingfaviconRequestHandlerorg.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapterdefaultViewResolverrequestContextFilterviewResolverspring.resources.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.web.WebMvcAutoConfigurationhiddenHttpMethodFilterhttpPutFormContentFilterorg.springframework.boot.autoconfigure.jmx.JmxAutoConfigurationmbeanExporterobjectNamingStrategymbeanServerorg.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfigurationspringApplicationAdminRegistrarorg.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfigurationorg.springframework.aop.config.internalAutoProxyCreatororg.springframework.boot.autoconfigure.aop.AopAutoConfigurationorg.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfigurationspring.jta.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfigurationjdbcTemplatenamedParameterJdbcTemplateorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfigurationdataSourceorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfigurationdataSourceInitializerorg.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration$TomcatDataSourcePoolMetadataProviderConfigurationtomcatPoolDataSourceMetadataProviderorg.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfigurationspring.datasource.CONFIGURATION_PROPERTIESdataSourceInitializerPostProcessororg.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfigurationopenEntityManagerInViewInterceptororg.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfigurationorg.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationtransactionManagerjpaVendorAdapterentityManagerFactoryBuilderentityManagerFactoryspring.jpa.CONFIGURATION_PROPERTIESdataSourceInitializedPublisherorg.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfigurationorg.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfigurationpersistenceExceptionTranslationPostProcessororg.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfigurationorg.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessoremBeanDefinitionRegistrarPostProcessorjpaMappingContextjpaContextorg.springframework.boot.autoconfigure.mongo.MongoAutoConfigurationmongospring.data.mongodb.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfigurationjacksonObjectMapperBuilderspring.jackson.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfigurationjacksonObjectMapperorg.springframework.boot.autoconfigure.jackson.JacksonAutoConfigurationorg.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfigurationstringHttpMessageConverterspring.http.encoding.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfigurationmappingJackson2HttpMessageConverterorg.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfigurationorg.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfigurationmessageConvertersorg.springframework.data.web.config.HateoasAwareSpringDataWebConfigurationpageableResolversortResolverpagedResourcesAssemblerpagedResourcesAssemblerArgumentResolverorg.springframework.data.web.config.SpringDataJacksonConfigurationjacksonGeoModuleorg.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfigurationorg.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration$EntityLinksConfigurationentityLinksPluginRegistrycontrollerEntityLinksdelegatingEntityLinksorg.springframework.hateoas.config.HateoasConfigurationlinkRelationMessageSourceorg.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration$HypermediaConfigurationhalObjectMapperConfigurer_halObjectMapperorg.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$DefaultObjectMapperCustomizer#0org.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$Jackson2ModuleRegisteringBeanPostProcessor#0_linkDiscovererRegistryorg.springframework.hateoas.LinkDiscoverers#0defaultRelProviderannotationRelProviderrelProviderPluginRegistry_relProviderorg.springframework.boot.autoconfigure.hateoas.HypermediaHttpMessageConverterConfigurationhalMessageConverterSupportedMediaTypeCustomizerorg.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfigurationspring.hateoas.CONFIGURATION_PROPERTIESorg.springframework.transaction.annotation.ProxyTransactionManagementConfigurationorg.springframework.transaction.config.internalTransactionAdvisortransactionAttributeSourcetransactionInterceptororg.springframework.transaction.config.internalTransactionalEventListenerFactoryorg.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$TransactionManagementConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfigurationorg.springframework.boot.autoconfigure.transaction.TransactionAutoConfigurationtransactionTemplateorg.springframework.boot.autoconfigure.web.HttpEncodingAutoConfigurationcharacterEncodingFilterorg.springframework.boot.autoconfigure.web.MultipartAutoConfigurationmultipartConfigElementmultipartResolvermultipart.CONFIGURATION_PROPERTIESorg.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurationserverPropertiesduplicateServerPropertiesDetectororg.springframework.orm.jpa.SharedEntityManagerCreator#0SpringUtilTest(name=hongdada, age=31)
View Code

 

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

Spring通過ApplicationContext主動擷取bean

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.