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

    Jumping from failure to failure with undiminished enthusiasm is the big secret to success.
  • 相关阅读:
    编译原理:正则表达式
    编译原理:基于状态转换图识别for语句
    汇编小笔记
    win10汇编如何debug(小白向)
    nodejs模块引用
    nodejs环境设置理解
    分享几个看上去很酷炫的运算
    JavaScript数据结构 (手打代码)
    爬取煎蛋XXOO妹子图片
    Python Selenium官方文档阅读笔记
  • 原文地址:https://www.cnblogs.com/chongerlishan/p/5942033.html
Copyright © 2020-2023  润新知