学习Spring Boot 系列教程(1)纯手打 Java 搭建 SSM 项目

学习Springboot过程中,正常时不推荐XML配置注解,当然不推荐并非不支持,大学课程老师教授JavaEE课程学习Springboot就是用XML配置的。官网Springboot推荐开发者使用Java配置来搭建框架,Springboot中,大量的自动化配置都是通过Java配置来实现的,实现的方法我们也可以做出来,使用
纯Java来搭建一个SSM环境,就是项目中不存在任何的XML配置,包括类似webxml文件。
环境配置要求
使用纯 Java 来搭建 SSM 环境, Tomcat 的版本必须在 7 以上
快速开发体验

1 创建工程
创建一个普通的 Maven 工程(注意,这里可以不必创建 Web 工程),并添加 SpringMVC 的依赖,同时,这里环境的搭建需要用到 Servlet ,所以我们还需要引入 Servlet 的依赖(一定不能使用低版本的 Servlet),最终的 pom.xml 文件如下:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

2 添加 Spring 配置
工程创建成功之后,首先添加 Spring 的配置文件,如下:

@Configuration
@ComponentScan(basePackages = "myj",useDefaultFilters = true,excludeFilters = {@ComponentScan.Filter(type =
 FilterType.ANNOTATION,classes = Controller.class)})
public class SpringConfig {
}

关于这个配置,注意如下几点:

●@Configuration 注解表示这是一个配置类,在我们这里,这个配置的作用类似于 applicationContext.xml
●@ComponentScan 注解表示配置包扫描,里边的属性和 xml 配置中的属性都是一一对应的,useDefaultFilters 表示使用默认的过滤器,然后又除去 Controller 注解,即在 Spring 容器中扫描除了 Controller 之外的其他所有 Bean

3 添加 SpringMVC 配置
接下来再来创建 springmvc 的配置文件:

@Configuration
@ComponentScan(basePackages = "myj",useDefaultFilters = false,includeFilters = {@ComponentScan.Filter(type =
    FilterType.ANNOTATION,classes = Controller.class),@ComponentScan.Filter(type = FilterType.ANNOTATION,classes =
        Configuration.class)})
public class SpringMVCConfig {
}

注意,如果不需要在 SpringMVC 中添加其他的额外配置,这样就可以了。即 视图解析器、JSON 解析、文件上传……等等,如果都不需要配置的话,这样就可以了。

4 配置 web.xml
此时,我们并没有 web.xml 文件,这时,我们可以使用 Java 代码去代替 web.xml 文件,这里会用到 WebApplicationInitializer ,具体定义如下:

public class WebInit implements WebApplicationInitializer {
    @Override
    public void onStartup(javax.servlet.ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.setServletContext(servletContext);
        ctx.register(SpringMVCConfig.class);
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        springmvc.addMapping("/");
        springmvc.setLoadOnStartup(1);
    }
}

WebInit 的作用类似于 web.xml,这个类需要实现 WebApplicationInitializer 接口,并实现接口中的方法,当项目启动时,onStartup 方法会被自动执行,我们可以在这个方法中做一些项目初始化操作,例如加载 SpringMVC 容器,添加过滤器,添加 Listener、添加 Servlet 等。

猜你喜欢

转载自blog.csdn.net/qq_40771292/article/details/106989408