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();
sut.setName("hongdada");
sut.show(); }
}
因为比较懒,就没有创建其他类,直接在main里面运行的。
output:
beanNames个数:
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#
org.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$Jackson2ModuleRegisteringBeanPostProcessor#
_linkDiscovererRegistry
org.springframework.hateoas.LinkDiscoverers#
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#
SpringUtilTest(name=hongdada, age=)
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的更多相关文章
- Spring在代码中获取bean的几种方式
方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...
- Spring在代码中获取bean的几种方式(转:http://www.dexcoder.com/selfly/article/326)
方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObj ...
- Spring读取配置文件,获取bean的几种方式
BeanFactory有很多实现类,通常使用 org.springframework.beans.factory.xml.XmlBeanFactory类.但对于大部分J2EE应用而言,推荐使 用App ...
- Spring在代码中获取bean的几种方式(转)
获取spring中bean的方式总结: 方法一:在初始化时保存ApplicationContext对象 ApplicationContext ac = new FileSystemXmlApplica ...
- Spring工具类 非spring管理环境中获取bean及环境配置
SpringUtils.java import org.springframework.beans.BeansException; import org.springframework.beans.f ...
- Spring中applicationContext.xml的bean里的id和name属性区别
转自:http://www.cnblogs.com/ztf2008/archive/2009/02/11/1388003.html <beans><bean id="per ...
- 不用@Value从Spring的ApplicationContext中获取一个或全部配置
获取一个配置: applicationContext.getEnvironment().resolvePlaceholders("${propertyKey}"); // 方法1 ...
- spring Jdbc自己主动获取主键。
学习了下springjdbc,感觉挺有用的,相对来说springjdbc 扩展性相当好了 package com.power.dao; import java.lang.reflect.Paramet ...
- spring项目启动后,获取bean的方法总结
如果在web项目中,用到定时器的朋友可能会遇到使用spring注解的方式获取bean的时候报空指针的异常.这是就可以使用手工的方法获取spring容器中的bean了. 下面是具体的方法: 1.先说一个 ...
随机推荐
- short url短链接原理
一.什么是短链接 含义:就是把普通网址,转换成比较短的网址.比如:http://t.cn/RlB2PdD 这种,比如:微博:这些限制字数的应用里都用到这种技术. 优点:短.字符少.美观.便于发布.传播 ...
- TcMalloc的介绍以及Windows下安装使用
本文由博主(SunboyL)原创,转载请注明出处:http://www.cnblogs.com/xsln/p/Introduction_TcMalloc.html 介绍: TcMalloc(Threa ...
- crawlspider爬虫:定义url规则
spider爬虫,适合meta传参的爬虫(列表页,详情页都有数据要爬取的时候) crawlspider爬虫,适合不用meta传参的爬虫 scrapy genspider -t crawl it it. ...
- 3.cassandra遇到内存占用过高的问题
目前cssandra的内存分配如下: https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_tune_jvm_c.ht ...
- vertx异步编程测试
vertx是异步编程的框架,性能较高,开发简单.异步编程就是当一个请求来了,vertx将其交由一个事件进行处理,然后继续向下执行,等处理完成,返回结果,通知客户端.这是一个由服务端反向调用客户端的过程 ...
- IP设置-内置服务器-外置服务器
HBulider 中 运行 -> 设置web服务器 -> 内置服务器将 127.0.0.1 换为局域网的ip,可以在局域网内所有电脑,手机上浏览页面.但是只能浏览html,php asp等 ...
- shell应用技巧
Shell 应用技巧 Shell是一个命令解释器,是在内核之上和内核交互的一个层面. Shell有很多种,我们所使用的的带提示符的那种属于/bin/bash,几乎所有的linux系统缺省就是这种she ...
- mysql的count方法详解
1.cout(*)会统计为null的行: 2.count(列名)不会统计此列null值的行: 3.count(distinct col)计算该列除null之外的不重复数量:
- mysql的innodb存储引擎和myisam存储引擎的区别
主要区别如下: 1.事务支持.innodb支持事务,事务(commit).回滚(rollback)和崩溃修复能力(crash recovery capabilities)的事务安全(transacti ...
- 利用javascript实现css操作
在很多情况下,都需要对网页上元素的样式进行动态的修改.在JavaScript中提供几种方式动态的修改样式,下面将介绍方法的使用.效果.以及缺陷. 1.使用obj.className来修改样式表的类名. ...