在web.xml文件中配置
指定配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
声明web容器监听器
<listener>
<listener-class>com.hhkj.jike.util.SringContextLOaderListen</listener-class>
</listener>
SringContextLOaderListen该监听器需要继承监听器ContextLoaderListener
----------------------------------------------------------------------------
SringContextLOaderListen类代码如下
public class SringContextLOaderListen extends ContextLoaderListener {
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
super.contextDestroyed(event);
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
super.contextInitialized(event);
System.out.println("成功");
ServletContext context = event.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); //获取applicationContext
SpringContentUtil.setApplicationContext(ctx); //将applicationContext 放入到SpringContentUtil类的静态变量中存储起来
}
@Override
protected ContextLoader createContextLoader() {
// TODO Auto-generated method stub
return super.createContextLoader();
}
@Override
public ContextLoader getContextLoader() {
// TODO Auto-generated method stub
return super.getContextLoader();
}
}
-------------------------------------------------------------------------
SpringContentUtil 代码如下
public class SpringContentUtil {
private static ApplicationContext context;
public static void setApplicationContext(ApplicationContext acx) {
context = acx;
}
public static ApplicationContext getApplicationContext() {
return context;
}
public static Object getBean(String name) throws BeansException {
return context.getBean(name);
}
public static Object getBean(String name, Class requiredType) throws BeansException {
return context.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return context.containsBean(name);
}
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return context.isSingleton(name);
}
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return context.getType(name);
}
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return context.getAliases(name);
}
}
------------------------------------------------------
service中类写法
@Service("ling")
public class ImageUrlServiceImpl implements ImageUrlService {
@Resource GenericDao basedao;
。。。。。。。。。。
}
----------------------------------------
调用获取上述service
ImageUrlService imageUrl = (ImageUrlService) SpringContentUtil.getBean("ling");
至此imageUrl变可调用该内中的一切执行方法