非Controller类无法使用Service bean解决方案

 

 

尝试方案: 1 在Spring的配置文件springmvc.xml中,增加扫描项base-package="zxs.ssm.util",增加你需要使用service的类所在的包 <context:component-scan base-package="zxs.ssm.controller,zxs.ssm.util"> 然后在相应的类上加上注解@Component 解决方案: 1 在web.xml文件中增加类监听器,例如:   <listener>    <listener-class>zxs.ssm.util.SpringInit</listener-class>   </listener> 2 编写类SpringInit

package zxs.ssm.util;

import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener;

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

public class SpringInit implements ServletContextListener {        

          private static WebApplicationContext springContext;    

          public SpringInit() {        

                          super();  

          }    

         public void contextInitialized(ServletContextEvent event) {       

                       springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());   

         }    

        public void contextDestroyed(ServletContextEvent event) {     }    

        public static ApplicationContext getApplicationContext() {     

                          return springContext;    

        }

}

3 即可在非Controller类中直接使用Service类(注意:需要使用配置文件中定义好的bean名称)  DepartmentService depService = (DepartmentService)SpringInit.getApplicationContext().getBean("depService");

posted @ 2016-10-09 14:10  虫儿ls  Views(1436)  Comments(0Edit  收藏  举报