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

来源:互联网 发布:xmlbar软件下载 编辑:程序博客网 时间:2024/05/17 21:47

1、思路 
因为不是在@Controller类中,使用@Autowired注解是得不到Service类的,所以可以通过手动方式进行获取。

2、配置(如果已经配置好了,并且能在@Controller中获得service类可以跳过这个) 
为了更好的区分,所以spring mvc的xml配置进行了分层,每个目录管理每个层次的东西,层次分明。

在web.xml文件中配置srping的上线文。

在springmvc.xml中配置控制层的扫描

在applicationContext-service.xml中配置service的配置

配置好了的话在正常情况下使用@Controller、@RequestMapping进行说明,配合使用@Autowired注解说明这个service类,就可以获得该类进行使用。

3、在非Controller类无法使用Service 
由于不是在Controller类,所以使用@Autowired注解说明这个service类是没有用的,无法获取这个类,这个类还是null。 
(1)首先在web.xml文件中配置一个监听,启动的时候就运行这个监听

<!-- 监听(作用就是在非@Controller使用Service类首先需要实现该SpringInit类)-->    <listener>            <listener-class>                 com.ssm.app.core.util.SpringInit       </listener-class>     </listener>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

(2)SpringInit类(这个类的目的是获取这个类的对象,为后续获取Service做准备)

package com.ssm.app.core.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;           }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

(3)假设我要在一个非Controller类中获取service类 
只需要在改类或需要调用该类的方法中加入这段代码:

AppCdService appcdService = (AppCdService)SpringInit.getApplicationContext().getBean("AppCdService");
  • 1

解释: 
(1)AppCdService appcdService 
是我需要的Service类,就相当@Autowired注解是需要的类,需要用我需要的类进行接收 
(2)SpringInit.getApplicationContext().getBean(“AppCdService”)

SpringInit这个是监听类的名称,需要导入这个类相关包,

getApplicationContext()是这个类的方法

getBean(“AppCdService”)是获取Bean方法,其中AppCdService是applicationContext-service.xml中配置的中的id名称,代表想取出那个Service进行注解。最后进行强转为该Service。期间需要注意配置需要配对

阅读全文
0 0
原创粉丝点击