获取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> T getBean(String name){
		return (T)ac.getBean(name) ;
	}
	
	public static <T> T getBean(Class<T> 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配置文件里要加上:

<bean id="springHodler" class="com.ioc.SpringContextHodler"></bean>


在J2EE中:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值