2 SpringMVC 入门案例


文章目录

  • SpringMVC
  • 2 SpringMVC 入门案例
  • 2.5 bean 加载控制
  • 2.5.3 环境准备
  • 2.5.4 设置bean 加载控制


2.5 bean 加载控制
2.5.3 环境准备

创建一个新的Web Maven 项目模块

spring excludeFilters 排除无效_spring

完善目录结构【后面再用骨架创建的咱就不提这个事儿了】

spring excludeFilters 排除无效_java_02

pom.xml添加Spring依赖

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http:///POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http:///POM/4.0.0 http:///xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.dingjiaxiong</groupId>
    <artifactId>springmvc_02_bean_load</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>80</port>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

创建对应的配置类

package com.dingjiaxiong.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * ClassName: SpringMvcConfig
 * date: 2022/9/18 12:58
 *
 * @author DingJiaxiong
 */

@Configuration
@ComponentScan("com.dingjiaxiong.controller")
public class SpringMvcConfig {
}
package com.dingjiaxiong.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * ClassName: SpringConfig
 * date: 2022/9/18 12:58
 *
 * @author DingJiaxiong
 */

@Configuration
@ComponentScan("com.dingjiaxiong")
public class SpringConfig {
}
package com.dingjiaxiong.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

/**
 * ClassName: ServletContainersInitConfig
 * date: 2022/9/18 12:57
 *
 * @author DingJiaxiong
 */

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        return context;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

编写Controller,Service,Dao,Domain类

package com.dingjiaxiong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * ClassName: UserController
 * date: 2022/9/18 12:59
 *
 * @author DingJiaxiong
 */

@Controller
public class UserController {
    
    @RequestMapping("/save")
    @ResponseBody
    public String save(){
        System.out.println("user save ...");
        return "{'info':'springmvc'}";
    }
    
}
package com.dingjiaxiong.domain;

/**
 * ClassName: User
 * date: 2022/9/18 13:01
 *
 * @author DingJiaxiong
 */

public class User {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
         = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.dingjiaxiong.service;

import com.dingjiaxiong.domain.User;

/**
 * ClassName: UserService
 * date: 2022/9/18 13:00
 *
 * @author DingJiaxiong
 */

public interface UserService {
    public void save(User user);
}
package com.dingjiaxiong.service.impl;

import com.dingjiaxiong.domain.User;
import com.dingjiaxiong.service.UserService;
import org.springframework.stereotype.Service;

/**
 * ClassName: UserServiceImpl
 * date: 2022/9/18 13:02
 *
 * @author DingJiaxiong
 */

@Service
public class UserServiceImpl implements UserService {
    @Override
    public void save(User user) {
        System.out.println("user service ...");
    }
}
package com.dingjiaxiong.dao;

import com.dingjiaxiong.domain.User;
import org.apache.ibatis.annotations.Insert;

/**
 * ClassName: UserDao
 * date: 2022/9/18 13:03
 *
 * @author DingJiaxiong
 */

public interface UserDao {

    @Insert("insert into tbl_user(name,age)values(#{name},#{age})")
    public void save(User user);

}
2.5.4 设置bean 加载控制

【方式一:修改Spring配置类,设定扫描范围为精准范围。】

spring excludeFilters 排除无效_mybatis_03

上述只是通过例子说明可以精确指定让Spring扫描对应的包结构,真正在做开发的时候,因为Dao最终是交给MapperScannerConfigurer对象来进行扫描处理的,只需要将其扫描到service包即可。

【方式二:修改Spring配置类,设定扫描范围为com.itheima,排除掉controller包中的bean】

spring excludeFilters 排除无效_spring_04

  • excludeFilters属性:设置扫描加载bean时,排除的过滤规则
  • type属性:设置排除规则,当前使用按照bean定义时的注解类型进行排除
  • ANNOTATION:按照注解排除【记住这个】
  • ASSIGNABLE_TYPE:按照指定的类型过滤
  • ASPECTJ:按照Aspectj表达式排除,基本上不会用
  • REGEX:按照正则表达式排除
  • CUSTOM:按照自定义规则排除
  • classes属性:设置排除的具体注解类,当前设置排除@Controller定义的bean

【测试Controller类是否已经被排除】

package com.dingjiaxiong;

import com.dingjiaxiong.config.SpringConfig;
import com.dingjiaxiong.controller.UserController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * ClassName: App
 * date: 2022/9/18 13:10
 *
 * @author DingJiaxiong
 */

public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        System.out.println(context.getBean(UserController.class));//如果被排除了,这里会出现找不到的错误
    }
}

运行结果

spring excludeFilters 排除无效_mybatis_05

出现这个问题的原因:

  • Spring配置类扫描的包是com.dingjiaxiong
  • SpringMVC的配置类,SpringMvcConfig上有一个@Configuration注解,也会被Spring扫描到
  • SpringMvcConfig上又有一个@ComponentScan,把controller类又给扫描进来了所以如果不把@ComponentScan注释掉,Spring配置类将Controller排除,但是因为扫描到SpringMVC的配置类,又将其加载回来,演示的效果就出不来
  • 解决方案,也简单,把SpringMVC的配置类移出Spring配置类的扫描范围即可。

最后一个问题,有了Spring的配置类,要想在tomcat服务器启动将其加载,需要修改ServletContainersInitConfig

spring excludeFilters 排除无效_ide_06

对于上述的配置方式,Spring还提供了一种更简单的配置方式,可以不用再去创建AnnotationConfigWebApplicationContext对象,不用手动register对应的配置类

package com.dingjiaxiong.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

/**
 * ClassName: ServletContainersInitConfig
 * date: 2022/9/18 12:57
 *
 * @author DingJiaxiong
 */

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

【知识点1:@ComponentScan】

spring excludeFilters 排除无效_java_07