因爲公司開始用springBoot也有大半年了,今天閒來無事準備將springBoot的一些知識記錄下來,俗話說好記性不如爛筆頭。這樣也方便之後本身複習知識點。ok,廢話很少說,下面是講解下springBoot集成mybatis、swagger、logback。java
一、先看下工程目錄結構mysql
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.6.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.7</java.version> <spring.boot.version>1.3.5.RELEASE</spring.boot.version> <springfox-swagger2.version>2.5.0</springfox-swagger2.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!--JSP start--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!--JSP end--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>${spring.boot.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox-swagger2.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox-swagger2.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>${spring.boot.version}</version> <!-- 先排除tomcat-jdbc的默認配置dataSource --> <exclusions> <exclusion> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.10</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.16</version> </dependency> </dependencies> <build> <finalName>springboot</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/**</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/**</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
spring: mvc: view: prefix: /WEB-INF/jsp/ suffix: .jsp aop: auto: true http: encoding: charset: UTF-8 enabled: true force: true #profiles : dev datasource: name: test url: jdbc:mysql://localhost:3306/test username: root password: root ###### 使用druid數據源 ############ type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver 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 # redis: # database: 0 # host: 192.168.1.11 # port: 6379 # password: Admin123# # pool: # max-active: 1024 # max-idle: 200 # max-wait: 1000 #mybatis: # mapperLocations: classpath*:com/demo/dao/sql/*.xml # typeAliasesPackage: com.demo.entity server: port: 8180 context-path: /springboot
package com.demo.common; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; /** * Created by Administrator on 2017/3/19. */ @Configuration @EnableTransactionManagement @MapperScan("com.demo.dao") public class DataBaseConfig { private static final Logger log = LoggerFactory.getLogger(DataBaseConfig.class); @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { log.debug("Configuring Datasource"); return new DruidDataSource(); } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Bean public SqlSessionFactory sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:com/demo/dao/sql/*.xml")); return sqlSessionFactoryBean.getObject(); } }
五、這裏順便將swagger的配置也貼出git
package com.demo.common; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.async.DeferredResult; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static com.google.common.base.Predicates.or; import static springfox.documentation.builders.PathSelectors.regex; /** * Created by Administrator on 2017/3/19. */ @EnableSwagger2 @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .groupName("demo") .genericModelSubstitutes(DeferredResult.class) .useDefaultResponseMessages(false) .forCodeGeneration(false) .pathMapping("/") .select() .paths(or(regex("/api/.*"))) .build() .apiInfo(demoApiInfo()); } private ApiInfo demoApiInfo() { ApiInfo apiInfo = new ApiInfo( "SPRING BOOT AND SWAGGER TEST API",//大標題 "Test REST API, all the applications could access the Object model data via JSON.",//小標題 "1.0",//版本 "NO terms of service",//服務條款 "xxx.com",//做者 "Spring Boot Demo",//連接顯示文字 "http://localhost:8180/springboot/"//網站連接 ); return apiInfo; } }
六、ok,基於上面步驟springBoot的相關配置工做已作好,下面就是正常的springMVC的代碼,entity類github
package com.demo.entity.param; import io.swagger.annotations.ApiModelProperty; /** * Created by Administrator on 2017/3/19. */ public class StudentParam { @ApiModelProperty(value = "學生Id", required = true) private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
package com.demo.entity.result; import java.io.Serializable; public class Student implements Serializable{ private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
七、DAO類web
package com.demo.dao; import com.demo.entity.result.Student; /** * Created by Administrator on 2017/3/19. */ public interface StudentDao { Student findStudent(Integer id); }
八、DAO對應的xmlredis
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.demo.dao.StudentDao"> <select id="findStudent" resultType="com.demo.entity.result.Student" parameterType="Integer"> select id,name from student WHERE id = #{id} </select> </mapper>
九、Service類spring
package com.demo.service; import com.demo.entity.result.Student; /** * Created by Administrator on 2017/3/19. */ public interface StudentService { Student findStudent(Integer id); }
十、ServiceImpl類sql
package com.demo.service.impl; import com.demo.dao.StudentDao; import com.demo.entity.result.Student; import com.demo.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by Administrator on 2017/3/19. */ @Service public class StudentServiceImpl implements StudentService { @Autowired StudentDao studentDao; @Override public Student findStudent(Integer id) { return studentDao.findStudent(id); } }
十一、Controller類apache
package com.demo.rest; import com.demo.entity.param.StudentParam; import com.demo.entity.result.Student; import com.demo.service.StudentService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; /** * Created by Administrator on 2017/3/19. */ @RestController @RequestMapping("api/") @Api(description = "swagger測試接口SweggerController",tags = {"SweggerController"}) public class StudentRestController { @Autowired private StudentService studentService; @ApiOperation(value = "獲取學生信息接口" , notes = "swagger測試接口") @RequestMapping(value = "student/_search",method = RequestMethod.POST,produces = {MediaType.APPLICATION_JSON_VALUE}) public Student getStudent(@RequestBody StudentParam param){ return studentService.findStudent(param.getId()); } }
十二、關於logback的配置,打印日誌,sql語句至控制檯json
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="false"> <property name="BasePath" value="${user.dir}/spring-boot-log" /> <property name="BaseName" value="spring-boot-log" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>[%d{yyyy/MM/dd HH:mm:ss.SSS}][%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <appender name="rollingAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${BasePath}/${BaseName}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${BasePath}/${BaseName}.%d{yyyyMMdd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>[%d{yyyy/MM/dd HH:mm:ss.SSS}][%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <append>false</append> <prudent>false</prudent> </appender> <appender name="serviceAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${BasePath}/${BaseName}-service.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${BasePath}/${BaseName}-service.%d{yyyyMMdd}.log</fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder><!-- 必須指定,不然不會往文件輸出內容 --> <pattern>[%d{yyyy/MM/dd HH:mm:ss.SSS}][%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <append>false</append> <prudent>false</prudent> </appender> <logger name="com.demo" level="DEBUG" additivity="true"> <appender-ref ref="rollingAppender" /> </logger> <logger name="sql" level="DEBUG" additivity="true"> <appender-ref ref="rollingAppender" /> </logger> <logger name="com.ibatis" level="DEBUG" /> <logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG" /> <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG" /> <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG" /> <logger name="java.sql.Connection" level="DEBUG" /> <logger name="java.sql.Statement" level="DEBUG" /> <logger name="java.sql.PreparedStatement" level="DEBUG" /> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>
1三、最後一步springboot啓動類
package com.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by Administrator on 2017/3/19. */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
1四、運行實例
1五、控制檯sql語句日誌
最後附上demo代碼,github地址 https://github.com/xiaofeng010766/springboot-test.git