SpringContextUtil 的配置和调用

时间:2023-03-08 16:57:49

首先:在springmvc里面配置

<bean id="springContextUtil" class="com.hna.hka.rmc.common.util.SpringContextUtil" lazy-init="false"></bean>

然后编写工具类:

package com.ece.manager.web.controller;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext(){
return applicationContext;
}

public static Object getBean(String beanName){
return applicationContext.getBean(beanName);
}

public static Object getBean(Class c){
return applicationContext.getBean(c);
}
}

最后是java的调用:

static PaylogService paylogService = (PaylogService)SpringContextUtil.getBean("paylogService");

注意:用这个方法,在本地编写main方法无法测试,必须发布到tomcat