码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-01-20 17:58:09      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:java   spring   bean   web应用   tomcat   


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方法

标签:java   spring   bean   web应用   tomcat   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!