欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 的整合

程序员文章站 2022-05-01 13:00:35
...

工程架构

----SpringbootDemo
    ---SpringbootDemo.api
    ---SpringbootDemo.impl
    ---SpringbootDemo.controller
    ---SpringbootDemo.web
    -pom.xml
----SpringbootDemo.api
    ---com.java
    ---com.resource
    -pom.xml
----SpringbootDemo.impl
    ---com.java
    ---com.resource
    -pom.xml
----SpringbootDemo.controller
    ---com.java
    ---com.resource
    -pom.xml
----SpringbootDemo.web
    ---com.java
    ---com.resource
    ---src
        ---main.webapp
    -pom.xml

部分整合

Spring boot 倡导的是无配置,所以配置文件很少,先提供个主配置的文件,使用的是application.yml
使用yml 的原因很简单,格式化好,配置更清晰

server:
  port: 9090
  context-path: /springboot
  tomcat.basedir: D:/springboot-tomcat-tmp

spring:
    datasource:
        name: COASTFE531
        url: jdbc:sqlserver://CANGZDWCOA02:1433;DatabaseName=COASTFE531;integratedSecurity=false
        username: COASTQAID
        password: Coast@123
        driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver 
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

    # HTTP ENCODING  
    http:  
        encoding.charset: UTF-8  
        encoding.enable: true  
        encoding.force: true  
    mvc:
        view.prefix: /WEB-INF/jsp/
        view.suffix: .jsp

# MyBatis
mybatis:
    typeAliasesPackage: com.springboot.demo.vo
    mapperLocations: classpath*:com/springboot/demo/dao/*.xml

使用的日志是Logback,原因很简单,快,快,快

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds">
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 [%C.%M]-[%L] 
                包名,方法,行数 -->
            <pattern>[%date{HH:mm:ss.SSS}]-[%r]-[%t]-[%X{requestId}]-[%X{userId}]-[%p]-[%logger{5}]-[%C.%M]-[%L]    %.-10000m%n</pattern>
        </encoder>
    </appender>

    <appender name="springboot"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>logs/logback/springboot_%d{yyyy-M-d}.log
            </FileNamePattern>
            <MaxHistory>10</MaxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%thread]-[%-5level]-[%C.%M]-[%L]-%msg%n</pattern>
        </encoder>
    </appender>

    <appender name="smile"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>logs/logback/smile_%d{yyyy-M-d}.log
            </FileNamePattern>
            <MaxHistory>10</MaxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}]-[%thread]-[%-5level]-[%C.%M]-[%L]-%msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework.boot" level="debug" additivity="false">
        <appender-ref ref="springboot" />
    </logger>

    <!-- mybatis日志打印 -->
    <logger name="com.springboot.demo.dao" level="DEBUG">
        <appender-ref ref="stdout" />
    </logger>

    <!-- name包必须能够扫描到所以类,包括启动类 -->
    <logger name="com.springboot.demo" level="debug" additivity="false">
        <appender-ref ref="stdout" />
    </logger>

    <logger name="org.springframework.scheduling" level="info" />

    <logger name="org.springframework.web" level="debug">
        <appender-ref ref="stdout" />
    </logger>  

    <root level="DEBUG">
        <appender-ref ref="stdout" />
        <appender-ref ref="springboot" />
        <appender-ref ref="smile" />
    </root>
</configuration> 
Spring boot 的启动,无需配置Tomcat,直接Main 方法启
/**
 * @author ASNPHQC
 *
 */
package com.springboot.demo.main;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableScheduling  //开启定时器
@ComponentScan({"com.springboot.demo"})
@MapperScan({"com.springboot.demo.dao"})//扫描mapper 接口
@EnableSwagger2 //开启swagger
public class Application{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@ComponentScan

@ComponentScan告诉Spring 哪个packages 的用注解标识的类 会被spring自动扫描并且装入bean容器。

例如,如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan,自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,因此你配置的这个Controller也没有意义。

@SpringBootApplication

@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
分开解释@Configuration,@EnableAutoConfiguration,@ComponentScan。
1、@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。

<beans>  
    <bean id = "car" class="com.test.Car">  
        <property name="wheel" ref = "wheel"></property>  
    </bean>  
    <bean id = "wheel" class="com.test.Wheel"></bean>  
</beans> 

@Configuration的注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。
2、@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。

3、@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

@MapperScan
扫描所有的Mapper接口

@EnableSwagger2
待定……

Swagger 的集成

配置文件的实现

package com.springboot.demo.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration//配置
public class Swagger2 extends WebMvcConfigurerAdapter{

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot RESTful APIs")
                .description("关注我 CSDN博客 http://blog.csdn.net/HZMand1")
                .termsOfServiceUrl("http://blog.csdn.net/HZMand1")
                .version("1.0")
                .build();
    }
}

编写API

package com.springboot.demo.swagger.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.demo.vo.SimpleDemoVO;

/**
 * used create RESTFull API
 * @author ASNPHQC
 * @Api:修饰整个类,描述Controller的作用
 * @ApiOperation:描述一个类的一个方法,或者说一个接口
 * @ApiParam:单个参数描述
 * @ApiModel:用对象来接收参数
 * @ApiProperty:用对象接收参数时,描述对象的一个字段
 * @ApiResponse:HTTP响应其中1个描述
 * @ApiResponses:HTTP响应整体描述
 * @ApiIgnore:使用该注解忽略这个API
 * @ApiError :发生错误返回的信息
 * @ApiImplicitParam:一个请求参数
 * @ApiImplicitParams:多个请求参数
 * 访问路径 : http://localhost:9090/springboot/swagger-ui.html
 */
@Api(value = "SwaggerController")
@RestController
public class SwaggerController {

    @ApiOperation(value = "Get SimpleDemo By Id",notes = "Get SimpleDemo by URL id")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "getSimpleDemoById/{id}", method = RequestMethod.GET)
    public SimpleDemoVO getSimpleDemoById(@PathVariable(value = "id") Integer id){
        SimpleDemoVO simpleDemoVO = new SimpleDemoVO();
        simpleDemoVO.setId(String.valueOf(id));
        return simpleDemoVO;
    }

    /**
     * 查询用户列表
     * @return
     */
    @ApiOperation(value="Get SimpleDemo List", notes="Get SimpleDemo List")
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public List<SimpleDemoVO> getSimpleDemoList(){
        List<SimpleDemoVO> list = new ArrayList<SimpleDemoVO>();
        SimpleDemoVO demoVO = new SimpleDemoVO();
        demoVO.setId("1");
        demoVO.setPassWord("11");
        demoVO.setUserName("111");
        list.add(demoVO);

        SimpleDemoVO demoVO2 = new SimpleDemoVO();
        demoVO2.setId("2");
        demoVO2.setPassWord("22");
        demoVO2.setUserName("222");
        list.add(demoVO2);
        return list;
    }
}

上面这个类上提供了 页面的访问方法

定时任务的实现

package com.springboot.demo.autotest.impl;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class AutoTest {
    private static Logger log = Logger.getLogger(AutoTest.class);

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 如果测试的浏览器没有安装在默认目录,那么必须在程序中设置
        // bug1:System.setProperty("webdriver.chrome.driver",
        // "C://Program Files (x86)//Google//Chrome//Application//chrome.exe");
        // bug2:System.setProperty("webdriver.chrome.driver",
        // "C://Users//Yoga//Downloads//chromedriver_win32//chromedriver.exe");
        System.setProperty("webdriver.chrome.driver",
                "D:\\UT\\new_chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.baidu.com");
        // 获取 网页的 title
        System.out.println("The testing page title is: " + driver.getTitle());
        // driver.quit();
    }

    // 每天8点29 分执行
    @Scheduled(cron = "0 28 8 ? * *")
    private void myTest() {
        System.out.println("打卡上班");
        autoClockIn();
    }

    // 两秒执行一次
    @Scheduled(fixedRate = 1000 * 2)
    private void onTimeTestd() {
        log.debug("还活着");
    }

    private void autoClockIn() {
        System.setProperty("webdriver.chrome.driver", "D:\\UT\\new_chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("");
        driver.findElement(By.name("B1")).click();
    }
}

父工程的pom 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo.springbootdemo</groupId>
    <artifactId>SpringbootDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>SpringbootDemo.web</module>
        <module>SpringbootDemo.api</module>
        <module>SpringbootDemo.controller</module>
        <module>SpringbootDemo.impl</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

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

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.11</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>5.0</version>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
        </dependency>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-remote-driver</artifactId>
            <version>2.53.0</version><!--$NO-MVN-MAN-VER$ -->
        </dependency>

        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>4.1.0</version><!--$NO-MVN-MAN-VER$ -->
        </dependency>

        <!-- SpringBoot整合Swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <!-- spring热部署 -->
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>