spring 获取bean的方式

一直想总结一下spring获取bean的方式,我只记录三种,自以为三种应该就够我用了。

1.在spring的配置文件中配置自动扫描<context:component-scan base-package="*"></context:component-scan>,*代表你要扫描的包。在你需要由spring管理的类头上加上@Component 注解,这样在需要用到此bean的地方用

@Autowired
private TestService  testService;

即可注入bean。

这种方式是我在项目中最常用也是感觉最方便的一种,这种方式在一般情况下都适用。


2.

ServletContext sc = request.getSession().getServletContext();


XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);


UserService userService = (UserService) cxt.getBean("userService");

这是第二种方式,我用这种方式主要是解决一种第一种方式解决不了的情况。举个例子,就是在web项目的Filter中需要获取spring管理的bean时,第一种方式是不能实现的。因为在项目启动时,初始化filter的时候,spring还没来得及扫描bean。这时就可以用这个方式来获取bean了。


3.实现ApplicationContextAware接口


  1. public class SpringContextUtil implements ApplicationContextAware {
  2. // Spring应用上下文环境
  3. private static ApplicationContext applicationContext;
  4. /**
  5. * 实现ApplicationContextAware接口的回调方法。设置上下文环境
  6. *
  7. * @param applicationContext
  8. */
  9. public void setApplicationContext(ApplicationContext applicationContext) {
  10. SpringContextUtil.applicationContext = applicationContext;
  11. }
  12. /**
  13. * @return ApplicationContext
  14. */
  15. public static ApplicationContext getApplicationContext() {
  16. return applicationContext;
  17. }
  18. /**
  19. * 获取对象
  20. *
  21. * @param name
  22. * @return Object
  23. * @throws BeansException
  24. */
  25. public static Object getBean(String name) throws BeansException {
  26. return applicationContext.getBean(name);
  27. }
  28. }

这种情况可以用在项目中写一个获取bean的工具类,这种方式可以处理事先不确定要获取哪个bean的业务情况。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值