1、Spring整合SpringMVC的框架原理分析

整合成功的表现:在controller(SpringMVC)中能成功的调用service(Spring)对象中的方法。要想在controller中调用service方法,就要注入service到controller中来,有service对象才可以调用service方法,方法是这样没有错,但是有一个问题,就是启动Tomcat之后试想一下,在web.xml中配置有前端控制器,web容器会帮我们加载springmvc.xml配置文件,在springmvc.xml配置文件中我们配置情况是只扫描controller,别的不扫,而spring.xml文件就从头到尾没有执行过,spring中的配置扫描自然也不会去扫描,就相当于没有将spring交到IOC容器当中去,所以,现在的解决方案就是,在启动服务器时就加载spring配置文件,怎么实现呢?这时候监听器listener就派上用场了,具体实现如下:

spring整合钉钉 spring整合springmvc_spring


2、在web.xml中配置ContextLoaderListener监听器

在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。要想加载applicationContext.xml的配置文件有两种方法,第一种(不建议):

spring整合钉钉 spring整合springmvc_spring整合钉钉_02


第二种(强烈建议):在web.xml中配置加载路径

<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.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>

至于为啥强烈建议第二种呢,是因为我们在整合过程中会有许多配置文件,我们自定义一个类似pages资源文件夹专门管理这些配置文件,方便管理,方便维护!!!
3、controller中注入service对象,调用service对象方法并测试
这时候,启动服务器时也会加载spring配置文件了,那么,我们可以在controller中注入service了,于是开始编写controller代码:

package com.gx.controller;

import com.gx.domain.Account;
import com.gx.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class AccountController {

    @Autowired   //按类型注入
    private AccountService accountService;

    @RequestMapping("/account/findAll")
    public String findAll(Model model){
        System.out.println("Controller表现层:查询所有账户...");

        List<Account> list = accountService.findAll();
        return "list";
    }
}

编写完成,开始测试,启动Tomcat,效果

spring整合钉钉 spring整合springmvc_java_03