Spring通过ApplicationContext主动获取bean

本文介绍了一种在Spring框架中通过Spring上下文手动获取Bean的方法,并提供了一个实用的工具类SpringUtil,该工具类可以帮助开发者在那些无法使用AutoWired和component注解的场景下获取到所需的Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有些场景无法通过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.youkuaiyun.com/jinzhencs/article/details/51673782

http://blog.youkuaiyun.com/silyvin/article/details/70832415

http://blog.youkuaiyun.com/u014695188/article/details/52396880

http://timerbin.iteye.com/blog/2252886

<think>我们正在讨论的是如何在Spring框架中通过静态方法获取ApplicationContext,进而获取Bean实例。根据引用内容,我们可以实现一个类实现ApplicationContextAware接口,这样Spring容器在初始化时会将ApplicationContext注入到该类中。然后我们可以在这个类中提供一个静态方法,以便在其他地方通过这个静态方法获取ApplicationContext,进而获取Bean。步骤如下:1.创建一个类(通常称为SpringContextHolder)实现ApplicationContextAware接口。2.在该类中定义一个静态的ApplicationContext变量。3.在setApplicationContext方法中将传入的ApplicationContext赋值给静态变量。4.提供一个静态方法(如getApplicationContext)返回ApplicationContext。5.提供另一个静态方法(如getBean)用于获取Bean实例。注意:由于ApplicationContext是在Spring容器启动时注入的,因此要确保这个类被Spring管理(比如通过@Component注解)。下面是一个示例:</think>在Spring框架中,通过静态方法获取Bean实例需要以下步骤: ### 解决方案 1. **实现ApplicationContextAware接口** 创建工具类实现`ApplicationContextAware`接口,Spring容器初始化时会自动注入`ApplicationContext`实例: ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; // 静态变量接收容器实例[^1] } public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); } } ``` 2. **通过静态方法获取Bean** 在其他类的静态方法中直接调用工具类: ```java public class SomeUtils { public static void doSomething() { // 静态获取Bean实例 MyService service = SpringContextHolder.getBean(MyService.class); service.execute(); } } ``` ### 关键说明 - **实现原理**:Spring容器检测到`ApplicationContextAware`接口时,会在Bean初始化后自动调用`setApplicationContext()`注入容器实例[^1] - **线程安全**:静态`ApplicationContext`在容器启动后初始化,多线程访问安全 - **作用域限制**:无法在Bean初始化阶段使用(此时容器未完成注入) - **替代方案**:也可直接注入`ApplicationContext`到非静态字段,但不符合静态调用需求 ### 使用示例 ```java // 测试类 public class Main { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyBean bean = SpringContextHolder.getBean(MyBean.class); // 静态获取[^3] bean.run(); } } ``` > **注意**:此方式会引入Spring依赖到静态上下文中,建议仅在工具类等特殊场景使用,优先使用常规依赖注入。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值