• Spring 外部注入Bean (JAX-WS)


          最近在SpringMvc中通过JAX-WS 来实现webservice,但是由于webservice没有在Spring容器中,所以需要Spring的dao,通过标签@Autowired 等方式得到的都是null 那么可以使用以下两种方式得到bean:

    第一种方法(spring4.0测试通过):

    web.xml注册

     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

     调用方法

    接口 obj=(接口)ContextLoaderListener.getCurrentWebApplicationContext().getBean("Bean名称");
    
    

    如果不知道Bean名称可以全部列出来看看:

    String []strs= ContextLoaderListener.getCurrentWebApplicationContext().getBeanDefinitionNames();
    
    for(int i=0;i<strs.length;i++){
             //   System.out.println(strs[i]);
            }
    
    

    第二种方法:

    第一种方法简单很多,但是如果不行,还可以使用下面这种方法

    首先写一个静态类

    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    public class WebContextSpringBeanFactory extends javax.servlet.http.HttpServlet {
    
    	public static WebApplicationContext webAppContext;
    
    	public void init(ServletConfig config) throws ServletException {
    
    		WebApplicationContext webAppContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
    		this.webAppContext = webAppContext;
    
    	}
    
    	/**
    	 *  
    	 * @param beanName
    	 * @return
    	 */
    	public static Object getBean(String beanName) {
    		System.out.println(webAppContext);
    		return webAppContext.getBean(beanName);
    
    	}
    
    }

    配置web.xml

    <servlet>
    		<servlet-name>WebContextSpringBeanFactory</servlet-name>
    		<servlet-class>WebContextSpringBeanFactory</servlet-class>
    		<load-on-startup>2</load-on-startup>
    	</servlet>

     如何使用?很简单:

    接口 obj=(接口)WebContextSpringBeanFactory.getBean("你的Bean");

  • 相关阅读:
    MongoDB 时间截取、字符串截取、拼接(时间戳、字符串等)
    ClickHouse 参数配置
    C++函数调用栈的变化分析
    WPF中为button添加快捷键(ShortCut)的方法
    vscode中一些好用的插件介绍
    剑指Offer 2. 青蛙跳台阶问题
    切片Slice的使用
    剑指Offer 1. 斐波那契数列
    match_parent和wrap_content的区别
    字节流、字符流
  • 原文地址:https://www.cnblogs.com/hiaming/p/8967830.html
Copyright © 2020-2023  润新知