获取Spring上下文

在J2SE中:

可以利用ApplicationContextAware,加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的
public void setApplicationContext(ApplicationContext context) throws BeansException

方法,获得ApplicationContext 对象。前提必须在Spring配置文件中指定该类。

package com.ioc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.aop.annotation.ILoginService;

public class SpringContextHodler implements InitializingBean,ApplicationContextAware{
	
	private static ApplicationContext ac ;
	
	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		SpringContextHodler.ac = arg0 ;
	}
	
	@SuppressWarnings("unchecked")
	public static  T getBean(String name){
		return (T)ac.getBean(name) ;
	}
	
	public static  T getBean(Class type){
		return ac.getBean(type) ;
	}

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		
		System.out.println(SpringContextHodler.getBean("loginService"));

		ILoginService loginService = (ILoginService) ctx
				.getBean("loginService");
		System.out.println(loginService);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("--------");
//		SpringHodler.ac = applicationContext ;
	}

}


在Spring配置文件里要加上:



在J2EE中:

 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();  
  ISysConfigDao sysconfigdao = (ISysConfigDao) wac.getBean("iSysConfigDao");  

你可能感兴趣的:(Spring)