Spring在代码中获取bean的几种方式

方法一:在初始化时保存ApplicationContext对象 :

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml"); 
ac.getBean("userService");

//比如:在application.xml中配置:
<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>

说明:这样的方式适用于Spring框架的独立应用程序,须要程序通过配置文件初始化Spring

方法二:通过Spring提供的工具类获取ApplicationContext对象

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 
ac1.getBean("beanId"); 
ac2.getBean("beanId");  

说明:这样的方式适合于採用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。

方法三:实现接口ApplicationContextAware:(推荐)

/**
 * Spring ApplicationContext 工具类
*/
@SuppressWarnings("unchecked")
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        if(applicationContext.containsBean(beanName)){
            return (T) applicationContext.getBean(beanName);
        }else{
            return null;
        }
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> baseType){
        return applicationContext.getBeansOfType(baseType);
    }
}

说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,扫描到该类,就会通过该方法将ApplicationContext对象注入。然后在代码中就可以获取spring容器bean了。例如:

LoadExploreTree bean = SpringUtils.getBean("loadExploreTree");

方法四:继承自抽象类ApplicationObjectSupport

@Service
public class SpringContextHelper2 extends ApplicationObjectSupport {
    
    
    //提供一个接口,获取容器中的Bean实例,根据名称获取
    public Object getBean(String beanName)
    {
        return getApplicationContext().getBean(beanName);
    }
    
}

继承类的方式,是调用父类的getApplicationContext()方法,获取Spring容器对象。

方法五:继承自抽象类WebApplicationObjectSupport

说明:类似上面方法。调用getWebApplicationContext()获取WebApplicationContext

 

 

 

  • 8
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值