1. 程式人生 > >Spring在web應用中獲得Bean的方法 實現getBean方法

Spring在web應用中獲得Bean的方法 實現getBean方法


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");