Spring+struts2项目启动时加载applicationContext.xml并获取 ApplicationContext对象

首先web.xml中加入如下监听器和上下文配置

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

 Action方法中修改如下:

public String execute() throws Exception {
       
        System.out.println("userAction...execute....");
        /*ApplicationContext context = 
                new ClassPathXmlApplicationContext("applicationContext.xml");*/
        HttpServletRequest request = ServletActionContext.getRequest();
        
        WebApplicationContext context = WebApplicationContextUtils.
            getRequiredWebApplicationContext(request.getServletContext());
        
        
        UserService userService = (UserService)context.getBean("userService");
        userService.add();
        return NONE;
    }    

 

posted @ 2018-10-11 19:25  annofyf  阅读(960)  评论(0编辑  收藏  举报