【Spring】普通类获取Spring容器的bean的方法

我们通常在项目中获取Spring容器里bean的方式,一般是使用注解的方式(@Autowired、@Resource)直接注入就可以直接使用了,那么如果在一个普通的类里(其他地方使用它的实例是以new的方式使用的),此时再用注解的方式注入的将会是null,那这种情况下,我们该如何使用Spring容器里的bean呢?本篇博客讲解五种方法,接下来就依次详细讲一下使用方式

一、在初始化时保存ApplicationContext对象

FileSystemXmlApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");
// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");

二、通过Spring提供的工具类获取ApplicationContext对象

WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");

三、继承自抽象类ApplicationObjectSupport

public class SpringTest extends ApplicationObjectSupport {
    private void test(){
   		// 1、使用类名获取
        XXX xxx = getApplicationContext().getBean(XXX.class);
        // 2、使用bean名获取
        Object yyy = getApplicationContext().getBean("beanName");

    }
}

四、继承自抽象类WebApplicationObjectSupport

```java
public class SpringTest extends WebApplicationObjectSupport{
    private void test(){
   		// 1、使用类名获取
        XXX xxx = getApplicationContext().getBean(XXX.class);
        // 2、使用bean名获取
        Object yyy = getApplicationContext().getBean("beanName");

    }
}

五、实现接口ApplicationContextAware

实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入
1、添加一个类,实现ApplicationContextAware

@Component
public class SpringContextService implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextService.applicationContext == null) {
            SpringContextService.applicationContext = applicationContext;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }
}

2、普通类的实际使用

// 1、使用类名获取
XXX xxx = SpringContextService.getBean(XXX.class);
// 2、使用bean名获取
Object yyy = SpringContextService.getBean("beanName");

以上就是普通类获取Spring容器的bean的几种方法,感谢您的阅读!

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值