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.Util;

import lombok.Data;
import lombok.ToString;
import org.springframework.stereotype.Component;


@Data
@ToString
@Component
public class SpringUtilTest {

    private String name;

    private int age;

    public void show(){
        System.out.println(this.toString());
    }
}

调用:

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)
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

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