Spring 外部注入Bean

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

第一种方法(spring4.0测试通过):
web.xml注册
Xml代码 收藏代码

org.springframework.web.context.ContextLoaderListener

调用方法
Java代码 收藏代码
接口 obj=(接口)ContextLoaderListener.getCurrentWebApplicationContext().getBean(“Bean名称”);

如果不知道Bean名称可以全部列出来看看:
Java代码 收藏代码
String []strs= ContextLoaderListener.getCurrentWebApplicationContext().getBeanDefinitionNames();

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

第二种方法:
第一种方法简单很多,但是如果不行,还可以使用下面这种方法
首先写一个静态类
Java代码 收藏代码
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
Xml代码 收藏代码

WebContextSpringBeanFactory
WebContextSpringBeanFactory
2

如何使用?很简单:
接口 obj=(接口)WebContextSpringBeanFactory.getBean(“你的Bean”);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值