Spring actively acquires beans through ApplicationContext

Source: Internet
Author: User

Some scenarios cannot be passed in via autowired and compoment annotations, so you want to take the initiative to get the beans through spring context
Demo

Package Com.qhong.util;import Org.springframework.context.ApplicationContext; Public classspringutil{Private StaticApplicationContext ApplicationContext =NULL;  Public Static voidSetapplicationcontext (ApplicationContext applicationcontext) {if(Springutil.applicationcontext = =NULL) {Springutil.applicationcontext=ApplicationContext; }    }    //Get ApplicationContext     Public StaticApplicationContext Getapplicationcontext () {returnApplicationContext; }    //gets the Bean by name.     Public StaticObject Getbean (String name) {returnGetapplicationcontext (). Getbean (name); }    //Gets the Bean by class.     Public Static<T> T Getbean (class<t>clazz) {        returnGetapplicationcontext (). Getbean (Clazz); }    //returns the specified bean through name, as well as Clazz     Public Static<T> T Getbean (String name,class<t>clazz) {        returnGetapplicationcontext (). Getbean (name, clazz); }}

Call:

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 classspringbootdemoapplication { Public Static voidMain (string[] args) {ApplicationContext ctx= Springapplication.run (springbootdemoapplication.class, args);        Springutil.setapplicationcontext (CTX); String[] Beannames=Ctx.getbeandefinitionnames (); System. out. println ("number of Beannames:"+beannames.length);  for(String bn:beannames) {System. out. println (BN); } springutiltest sut=springutil.getbean (springutiltest.class); Sut.setage ( to); Sut.setname ("Hongdada");    Sut.show (); }}

Because you are lazy, you do not create other classes that run directly inside main.

Output

Number of Beannames:177org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation . internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.spring Framework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.annotation.internalPersistenceA NnotationProcessororg.springframework.context.Event. InternalEventListenerProcessororg.springframework.context.Event. internalEventListenerFactoryspringBootDemoApplicationorg.springframework.context.annotation.ConfigurationClassPostProces Sor.importAwareProcessororg.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProce SsormongodbLogwebLogAspectspringUtilTesthelloControlleruserControllerorg.springframework.boot.autoconfigure.AutoConfigura TionPackagesorg.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurationorg.springframework.boot.autoconfi Gure.condition.BeanTypeRegistrypropertySourcesPlaceholderConfigurerorg.springframework.boot.autoconfigure.websocket.WebSo cketautoconfiguration$ TomcatWebSocketConfigurationwebsocketContainerCustomizerorg.springframework.boot.autoconfigure.websocket.WebSocketAutoCon figurationorg.springframework.boot.autoconfigure.web.embeddedservletcontainerautoconfiguration$ EmbeddedTomcattomcatEmbeddedServletContainerFactoryorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAut Oconfigurationembeddedservletcontainercustomizerbeanpostprocessororg.springframework.boot.autoconfigure.web.dispatcherservletautoconfiguration$ DispatcherServletConfigurationdispatcherServletdispatcherServletRegistrationspring.mvc.CONFIGURATION_ PROPERTIESorg.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessororg.springframework.boot . Context.properties.ConfigurationPropertiesBindingPostProcessor.storeorg.springframework.boot.autoconfigure.web.Dispatche rservletautoconfigurationorg.springframework.boot.autoconfigure.web.errormvcautoconfiguration$ WhitelabelErrorViewConfigurationerrorbeanNameViewResolverorg.springframework.boot.autoconfigure.web.ErrorMvcAutoConfigura Tionerrorattributesbasicerrorcontrollererrorpagecustomizerpreserveerrorcontrollertargetclasspostprocessororg.springframew ork.boot.autoconfigure.web.webmvcautoconfiguration$ Enablewebmvcconfigurationrequestmappinghandleradapterrequestmappinghandlermappingmvccontentnegotiationmanagerviewcontroll ErhandlermappingbeannamehandlermappingresoUrcehandlermappingmvcresourceurlproviderdefaultservlethandlermappingmvcconversionservicemvcvalidatormvcpathmatchermvcurlp Athhelpermvcuricomponentscontributorhttprequesthandleradaptersimplecontrollerhandleradapterhandlerexceptionresolvermvcvie wresolverorg.springframework.boot.autoconfigure.web.webmvcautoconfiguration$webmvcautoconfigurationadapter$ FaviconConfigurationfaviconHandlerMappingfaviconRequestHandlerorg.springframework.boot.autoconfigure.web.WebMvcAutoConfig uration$ WebMvcAutoConfigurationAdapterdefaultViewResolverrequestContextFilterviewResolverspring.resources.CONFIGURATION _propertiesorg.springframework.boot.autoconfigure.web.webmvcautoconfigurationhiddenhttpmethodfilterhttpputformcontentfilt Erorg.springframework.boot.autoconfigure.jmx.JmxAutoConfigurationmbeanExporterobjectNamingStrategymbeanServerorg.springfr Amework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfigurationspringApplicationAdminRegistrarorg.springframe Work.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfigurationorg. springframework.aop.config.internalAutoProxyCreatororg.springframework.boot.autoconf Igure.aop.AopAutoConfigurationorg.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfigurationspring.jta.CONFI guration_propertiesorg.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration$ JdbcTemplateConfigurationjdbcTemplatenamedParameterJdbcTemplateorg.springframework.boot.autoconfigure.jdbc.DataSourceAuto configuration$ nonembeddedconfigurationdatasourceorg.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration$ DataSourceInitializerConfigurationdataSourceInitializerorg.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoo lmetadataprovidersconfiguration$ TomcatDataSourcePoolMetadataProviderConfigurationtomcatPoolDataSourceMetadataProviderorg.springframework.boot.autoconfigu Re.jdbc.metadata.DataSourcePoolMetadataProvidersConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoCo Nfigurationspring.datasource.CONfiguration_ PROPERTIESdataSourceInitializerPostProcessororg.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration $JpaWebConfiguration $ JpaWebMvcConfigurationopenEntityManagerInViewInterceptororg.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfigurati on$ JpaWebConfigurationorg.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationtransactionManagerjpaVendo RAdapterentityManagerFactoryBuilderentityManagerFactoryspring.jpa.CONFIGURATION_ PROPERTIESdataSourceInitializedPublisherorg.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfigu Rationorg.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfigurationpersistenceExceptionTran Slationpostprocessororg.springframework.boot.autoconfigure.data.jpa.jparepositoriesautoconfigurationorg.springframework.d Ata.repository.core.support.RepositoryInterfaceAwareBeanPostProcessoremBeanDefinitionRegistrarPostProcessorjpaMappingCont ExtjpaContextorg.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.JacksonAutoConfiguratio norg.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.HttpMessageConvertersAutoConfiguratio Nmessageconvertersorg.spRingframework.data.web.config.HateoasAwareSpringDataWebConfigurationpageableResolversortResolverpagedResourcesAssemblerpa GedResourcesAssemblerArgumentResolverorg.springframework.data.web.config.SpringDataJacksonConfigurationjacksonGeoModuleor G.springframework.boot.autoconfigure.data.web.springdatawebautoconfigurationorg.springframework.boot.autoconfigure.hateoa s.hypermediaautoconfiguration$ EntityLinksConfigurationentityLinksPluginRegistrycontrollerEntityLinksdelegatingEntityLinksorg.springframework.hateoas.co Nfig. 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.HypermediaHttpMessageConverterConfigurationhalMessageConverterS UpportedMediaTypeCustomizerorg.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfigurationspring.hateoas.CONFI Guration_ PROPERTIESorg.springframework.transaction.annotation.ProxyTransactionManagementConfigurationorg.springframework.transacti On.config.internalTransactionAdvisortransactionAttributeSourcetransactionInterceptororg.springframework.transaction.confi G.internaltransactionaleventlistenerfactoryorg.springframework.boot.autoconfigure.jdbc.datasourcetransactionmanagerautoco nfiguration$ TransactionManagementConfigurationorg.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfigurati Onorg.springframework.boot.autoconfigure.transaction.transactionautoconfigurationtransactiontemplateorg.springframework.b Oot.autoconfigure.web.HttpEncodingAutoConfigurationcharacterEncodinGFilterorg.springframework.boot.autoconfigure.web.MultipartAutoConfigurationmultipartConfigElementmultipartResolvermultip Art. Configuration_ PROPERTIESorg.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurationserverPropertiesduplicateServerProp ertiesdetectororg.springframework.orm.jpa.sharedentitymanagercreator#0springutiltest (Name=hongdada, age= to)
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 actively acquires beans through ApplicationContext

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.