How to get spring application context object reference?

本文提供了一种方法,在非Spring管理的类中获取Spring应用上下文对象,通过实现ApplicationContextAware接口并创建自定义的ApplicationContextProvider类来实现。在ApplicationContext.xml文件中声明此bean,并在需要访问上下文的地方实例化ApplicationContextProvider,从而获取到所需的Bean引用。

This page gives an example to get spring application context object with in non spring managed classes as well. It is not possible to have all classes as spring managed classes, in such classes you need to get spring application context object. This can be achieved by using ApplicationContextAware interface. Here are the steps to achieve application context object:
Create a new class and implement ApplicationContextAware method and its unimplemented method as shown below:

package com.java2novice.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware{

    private static ApplicationContext context;

    public ApplicationContext getApplicationContext() {
        return context;
    }

    @Override
    public void setApplicationContext(ApplicationContext ac)
            throws BeansException {
        context = ac;
    }
}

Declate above bean in your applicationContext.xml file as shown below:

<bean id="applicationContextProvder"
                        class="com.java2novice.spring.ApplicationContextProvider"/>

And finally here is the code to access application context and getting bean reference:

ApplicationContextProvider appContext = new ApplicationContextProvider();
TestBean tb = appContext.getApplicationContext().getBean("testBean", TestBean.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值