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");

猜你喜欢

转载自inlhx.iteye.com/blog/2209532