您的位置:首页 > 移动开发 > Objective-C

How to get spring application context object reference?

2015-09-17 17:26 633 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring