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.先说一个 ...
随机推荐
- Ubuntu下安装vsftpd
1.sudo apt-get install vsftpd 2.修改配置文件 sudo gedit /etc/vsftpd.conf write_enable=YES ls_recurse_enabl ...
- 洛谷P3389 高斯消元 / 高斯消元+线性基学习笔记
高斯消元 其实开始只是想搞下线性基,,,后来发现线性基和高斯消元的关系挺密切就一块儿在这儿写了好了QwQ 先港高斯消元趴? 这个算法并不难理解啊?就会矩阵运算就过去了鸭,,, 算了都专门为此写个题解还 ...
- CentOS工作内容(三)配置网络IP地址
CentOS工作内容(三)配置网络IP地址 用到的快捷键 tab 自动补齐(有不知道的吗) ctrl+a 移动到当前行的开头(a ahead) ctrl+u 删除(剪切)此处至开始所有内容 vim 末 ...
- Spark Shuffle Write阶段磁盘文件分析
这篇文章会详细介绍,Sort Based Shuffle Write 阶段是如何进行落磁盘的 流程分析 入口处: org.apache.spark.scheduler.ShuffleMapTask.r ...
- Django初级手册3-视图层与URL配置
设计哲学 在Django中一个视图有指定函数和指定模版组成.对于某些特定的应用应该分成若干视图.例如博客系统 Blog主页面 详细页面入口 基于年的页面展示 基于月的页面展示 基于天的页面展示 评论行 ...
- Servlet—生命周期
首次访问 重复访问 换浏览器访问(说明在一次项目运行期间,servlet实例只会创建一个)
- 教你玩转产品管理系统iClap(基础功能篇)
距iClap这款宇宙级产品的推出已经有一段时间了,相信不少小伙伴们都已经开始使用上了,多好用多方便,就不用说了,可不想违反广告法呢!不过还是有用户反映说某些功能不太了解,或者还有一些不清楚的操作方式, ...
- Linux下DNS服务器配置
一步:yum install -y bind bind-utils bind-chroot yum install bind* //安装DNS服务 第二步:systemctl stop firewal ...
- python的数据结构之数字和字符串(四)
一.数字 Python Number 数据类型用于存储数值.数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间. Python 支持四种不同的数值类型: 整型( ...
- Linux服务器---配置apache支持php
apache支持php php是最好用的服务器语言了,Apache对php有很强大的支持 1.检测是否安装php,如果什么信息也没有,那么你就要自己安装php了 [root@localhost ~]# ...