springboot通过名称获取bean(applicationContext)

本文介绍了Spring框架中的IOC容器,包括beanFactory和ApplicationContext的区别,并重点讲解了如何使用ApplicationContext管理和获取beans。通过实现ApplicationContextAware接口,可以方便地从上下文中获取所需的bean实例。

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

IOC容器有beanFactory 和ApplicationContext.通常建议使用后者,因为它包含了前者的功能。Spring的核心是ApplicationContext.它负责管理 beans 的完整生命周期。我们可以从applicationContext里通过bean名称获取安装的bean.进行某种操作。不能直接使用applicationContext.而需要借助applicationContextAware.具体方法如下:

@Component
public class ApplicationContextHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public ApplicationContextHelper() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHelper.applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext != null?applicationContext.getBean(beanName):null;
    }
}

声明一个

ApplicationContextHelper组件,名字随意。它实现了ApplicationContextAware接口。并重写
setApplicationContext方法。在该组件里可以通过名字获取某个bean.
使用:
@SpringBootApplication
public class Application {

   public static void main(String[] args) {
      System.setProperty("user.timezone","Asia/Shanghai");
      TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
      SpringApplication.run(Application.class, args);
   }

   @Bean(name="restTemplate")
   public RestTemplate restTemplate() {
      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters()
            .add(0, new StringHttpMessageConverter( Charsets.UTF_8));
      return restTemplate;
   }
}

public class TestTask implements Callable<String> {

    private RestTemplate restTemplate = (RestTemplate) ApplicationContextHelper.getBean( "restTemplate" );
    public doSomeThing(){
    }
}
此外,不只可以通过名称,还可以通过属于某一类Class<T>,来获取类,例如,获取所有的requestHandler及其url映射,可以通过如下语句:
RequestMappingHandlerMapping handlerMapping = applicationContext.getBean(RequestMappingHandlerMapping.class);

关于RequestMappingHandlerMapping类,请参考:http://www.cnblogs.com/leftthen/p/5208404.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值