首页 > 编程语言 > 详细

Spring在web应用中获得Bean的方法 实现getBean方法

时间:2015-01-20 17:55:16      阅读:475      评论:0      收藏:0      [点我收藏+]


1.新建类,并实现 org.springframework.context.ApplicationContextAware 接口.

package com.abc.framework.util;

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

/**
 * 在容器启动后,也可以通过 getBean(String name) 得到对象
 * @author Administrator
 * <!-- 需要在spring.xml 里写 -->
 * <bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/>
 */
public class ApplicationContextHandle implements ApplicationContextAware{
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ApplicationContextHandle.applicationContext = applicationContext;
	}

	/** 
     * 获取对象 
     * 这里重写了bean方法,起主要作用 
     * @param name 
     * @return Object 一个以所给名字注册的bean的实例 
     * @throws BeansException 
     */  
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);  
    }
}

2.在spring.xml内添加:

<bean class="com.abc.framework.util.ApplicationContextHandle" lazy-init="false"/>

3.应用:

private static final AttachmentService as = (AttachmentService)ApplicationContextHandle.getBean("attachmentService");



Spring在web应用中获得Bean的方法 实现getBean方法

原文:http://blog.csdn.net/lpy3654321/article/details/42920997

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!