一个Bean扮演着应用程序素材的角色。它包含有一个functional interface,一个life-cycle interface,以及一个实现它所支援的商业方法的类别。下面小编为大家整理了关于Java类如何获取Spring的bean的文章,一起来看看吧:
1.创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.
示例代码:
view plaincopy to clipboardprint?
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;//声明一个静态变量保存
@Override
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
this.context=contex;
}
public static ApplicationContext getContext(){
return context;
}
2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.
例:
3.有了这个ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象。