SSH框架中 在别的地方获取service 不想注入。

1.重写 ContextLoaderListener  监听器。

package com.ucap.xzsp.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringLoaderListener extends ContextLoaderListener{
    
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // TODO Auto-generated method stub
        super.contextInitialized(event);
        ServletContext context=event.getServletContext();
        ApplicationContext ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        SpringContextutil.setContext(ctx);
        
    }

}



 2。新建一个辅助类。

package com.ucap.xzsp.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;

public class SpringContextutil {
    private static ApplicationContext context;

    public static ApplicationContext getContext() {
        return context;
    }

    public static void setContext(ApplicationContext context) {
        SpringContextutil.context = context;
    }
    
    public static Object getBean(String name)throws BeansException{
        return context.getBean(name);
    }

    @SuppressWarnings("unchecked")
    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);   
    }   
  
    @SuppressWarnings("unchecked")
    public static Class getType(String name) throws NoSuchBeanDefinitionException {   
        return context.getType(name);   
    }   
  
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {   
        return context.getAliases(name);   
    }   

    
}

5.在WEB.XML里面改变监听为重写的那个类

<listener>
        <listener-class>
            com.ucap.SpringLoaderListener
        </listener-class>
</listener>

 

 

4.获取service 对象。

XzspWebappQuestionService question=(XzspWebappQuestionService)SpringContextutil.getBean("xzspWebappQuestionService");

  

转载于:https://www.cnblogs.com/forbreak/archive/2012/06/01/2530937.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值