1. 程式人生 > >Spring Boot 的整合

Spring Boot 的整合

工程架構

----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>