package com.itheima.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppUtils {
private ApplicationContext ac;
public void getClassPathXmlApplicationContext(String xmlName){
if (ac ==null)
ac= new ClassPathXmlApplicationContext(xmlName);
}
public <T> void getAnnotationConfigApplicationContext(Class<T> t){
if (ac ==null)
ac= new AnnotationConfigApplicationContext(t);
}
public Object getBean(String name){
return ac.getBean(name);
}
public <T> T getBean(Class<T> tClass){
return ac.getBean(tClass);
}
}
要加static哟 再加个监听
package com.itheima.listener;
import com.itheima.utils.AppUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* @author 长沙黑马程序员
*/
@WebListener
public class ContextLoadListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// 当web工程部署到tomcat中,则ServletContext对象会创建,于是触发监听器的初始化方法
// 我们则将spring的IOC容器也初始化
AppUtils.initByXml("applicationContext.xml");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}