spring bean 不使用注入的方式获取的两种方式

非注入方式取得spring注入bean的util类实现

第一种,我用在webservice接口中。

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

/**
 * SpringBean的工具类<br>
 * 非注入方式取得spring注入bean的util类实现
 * @author langkai
 *
 */
public final class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext ctx;

    /**
     * 通过spring配置文件中配置的bean id取得bean对象
     * @param id spring bean ID值
     * @return spring bean对象
     */
    public static Object getBean(String id) {
        if (ctx == null) {
            throw new NullPointerException("ApplicationContext is null");
        }
        return ctx.getBean(id);
    }

	@Override
	public void setApplicationContext(ApplicationContext applicationcontext)
			throws BeansException {
		ctx = applicationcontext;
	}

}


实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入ApplicationContext的实例。

applicationContext.xml
<bean class="*.SpringBeanUtil"/>


这样在spring配置文件加载时会自动执行ApplicationContextAware的setApplicationContext方法,将applicationContext对象传递给我们的Util类。
SpringBeanUtil.getBean("myBean");

在某些时候我们不希望通过注入也能取得某些bean时有用。

PS:
Spring 中提供一些Aware相关接口,像是BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,这些 Aware接口的Bean在被初始之后,可以取得一些相对应的资源,例如实现BeanFactoryAware的Bean在初始后,Spring容器将会注入BeanFactory的实例,而实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例等等。

内容转载至: http://www.myexception.cn/software-architecture-design/897135.html

================================
第二种,就是传统的Application程序使用的了。

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springConfig_bus.xml");
		IMsgBusService client = (IMsgBusService) context.getBean("client");


猜你喜欢

转载自langmnm.iteye.com/blog/2002374