SpringBoot学习资料

发布时间:   来源:文档文库   
字号:
SpringBoot
一、Spring介绍
1.1SpringBoot简介
在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用SpringBoot来让你更易上手,更简单快捷地构建Spring应用!
SpringBoot让我们的Spring应用变的更轻量化。比如:你可以仅仅依靠一个Java类来运行一个Spring引用。你也可以打包你的应用为jar并通过使用java-jar来运行你的SpringWeb应用。SpringBoot的主要优点:为所有Spring开发者更快的入门
开箱即用,提供各种默认配置来简化项目配置嵌式容器简化Web项目
没有冗余代码生成和XML配置的要求
本章主要目标完成SpringBoot基础项目的构建,并且实现一个简单的Http请求处理,通过这个例子对SpringBoot有一个初步的了解,并体验其结构简单、开发快速的特性。
1.2、系统要求:
Java7及以上
SpringFramework4.1.5及以上
本文采用Java1.8.0_73SpringBoot1.3.2调试通过。
二、快速入门

2.1、创建一个Maven工程
名为”springboot-helloworld”类型为Jar工程项目


2.2pom文件引入依赖
<parent>

<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId><version>1.3.3.RELEASEversion>
parent><dependencies>
SpringBootweb组件-->
<dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>

spring-boot-starter-parent作用
pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么staterpoms,它可以提供dependencymanagement,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。
spring-boot-starter-web作用
springweb核心组件
spring-boot-maven-plugin作用
如果我们要直接Main启动spring那么以下plugin必须要添加,否则是无法启动的。如果使用mavenspring-boot:run话是不需要此配置的。(我在测试的时候,如果不配置下面的plugin也是直接在Main中运行的。)

2.3、编写HelloWorld服务
创建package命名为com.itmayiedu.controller(根据实际情况修改)

创建HelloController类,容如下

RestController
EnableAutoConfigurationpublicclassHelloController{
RequestMapping("/hello"publicStringindex({}
return"HelloWorld";
publicstaticvoidmain(String[]args{}
}
SpringApplication.run(HelloController.class,args;
2.4RestController
在上加上RestController表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口
2.5EnableAutoConfiguration
注解:作用在于让SpringBoot根据应用所声明的依赖来对Spring框架进行自动配置
SpringBootjarSpringspring-boot-starter-web添加了TomcatSpringMVC,所以auto-configuration将假定你正在开发一web应用并相应地对Spring进行设置。
2.6SpringApplication.run(HelloController.class,args;
标识为启动类2.6.1
SpringbootApplication
使用SpringbootApplication注解可以解决根类或者配置类(我自己的说法,就是main所在类)头上注解过多的问题,一个SpringbootApplication相当于Configuration,EnableAutoConfigurationComponentScan并具有他们的默认属性值
SpringBootApplication//等同于ConfigurationEnableAutoConfigurationComponentScanpublicclassApplication{
publicstaticvoidmain(String[]args{

SpringApplication.run(Application.class,args;}

2.7SpringBoot启动方式1
Springboot默认端口号为8080

RestController
EnableAutoConfigurationpublicclassHelloController{
RequestMapping("/hello"publicStringindex({}
return"HelloWorld";
publicstaticvoidmain(String[]args{}
}
SpringApplication.run(HelloController.class,args;

启动主程序,打开浏览器访问localhost:8080/index,可以看到页面输出HelloWorld
2.8SpringBoot启动方式2
ComponentScan(basePackages=".itmayiedu.controller"---控制器扫包围ComponentScan(basePackages=".itmayiedu.controller"EnableAutoConfigurationpublicclassApp{}
publicstaticvoidmain(String[]args{}
SpringApplication.run(App.class,args;




三、Web开发
3.1、静态资源访问
在我们开发Web应用的时候,需要引用大量的jscss、图片等静态资源。默认配置
SpringBoot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:/static/public/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问localhost:8080/D.jpg。如能显示图片,配置成功。
3.2、全局捕获异常
ExceptionHandler表示拦截异常
ooo
ControllerAdvicecontroller的一个辅助类,最常用的就是作为全局异常处理的切面类ControllerAdvice可以指定扫描围
ControllerAdvice约定了几种可行的返回值,如果是直接返回model类的话,需要使用
ResponseBody进行json转换
返回String,表示跳到某个view返回modelAndView
返回model+ResponseBody

ControllerAdvice
publicclassGlobalExceptionHandler{}
ExceptionHandler(RuntimeException.classResponseBody
publicMapexceptionHandler({}
Mapmap=newHashMap(;map.put("errorCode","101";map.put("errorMsg","系統错误!";returnmap;


3.3、渲染Web页面

渲染Web页面
在之前的示例中,我们都是通过RestController来处理请求,所以返回的容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?模板引擎
在动态HTML实现上SpringBoot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态。SpringBoot提供了默认配置的模板引擎主要有以下几种:

ThymeleafFreeMarkerVelocityGroovyMustache
SpringBoot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现SpringBoot的多种特性,具体可见后文:支持JSP的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
3.4、使用Freemarker模板引擎渲染web视图3.4.1pom文件引入:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>dependency>
3.4.2、后台代码
src/main/resources/创建一个templates文件夹,后缀为*.ftl


RequestMapping("/index"
publicStringindex(Mapmap{map.put("name","美丽的天使...";}
return"index";



3.4.3、前台代码




${name}


3.4.4Freemarker其他用法
RequestMapping("/index"
publicStringindex(Mapmap{map.put("name","###蚂蚁课堂###";map.put("sex",1;
Listuserlist=newArrayList(;userlist.add("余胜军";userlist.add("";userlist.add("";
map.put("userlist",userlist;return"index";}


</word><wordclass='41_1'>首页</word><wordclass='39_1'>
${name}<#ifsex==1>

<#elseifsex==2><#else>其他




<#listuserlistasuser>${user}


3.4.5Freemarker配置
新建application.properties文件
###########################################################FREEMARKER(FreeMarkerAutoConfiguration
########################################################spring.freemarker.allow-request-override=falsespring.freemarker.cache=true
spring.freemarker.check-template-location=truespring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.expose-spring-macro-helpers=false#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=#spring.freemarker.settings.*=spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/#comma-separatedlist
#spring.freemarker.view-names=#whitelistofviewnamesthatcanberesolved
3.5、使用JSP渲染Web视图3.5.1pom文件引入以下依赖
<parent>

<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId><version>1.3.3.RELEASEversion>
parent><dependencies>



<dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>
dependency><dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
dependency><dependency>
<groupId>org.apache.tomcat.embedgroupId><artifactId>tomcat-embed-jasperartifactId>
dependency>
dependencies>

3.5.2、在application.properties创建以下配置
spring.mvc.view.prefix=/WEB-INF/jsp/spring.mvc.view.suffix=.jsp

3.5.3、后台代码
Controller
publicclassIndexController{}
RequestMapping("/index"publicStringindex({
return"index";

}




四、据访问
4.1springboot整合使用JdbcTemplate
4.1.1pom文件引入
<parent>

<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId><version>1.5.2.RELEASEversion>
parent><dependencies>
<dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-jdbcartifactId>
dependency><dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId><version>5.1.21version>
dependency><dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-testartifactId><scope>testscope>
dependency><dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>

4.1.2application.properties新增配置
spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=root

spring.datasource.password=root
spring.datasource.driver-class-name=.mysql.jdbc.Driver

4.1.3UserService
Service
publicclassUserServiceImplimplementsUserService{}
Autowired
privateJdbcTemplatejdbcTemplate;
publicvoidcreateUser(Stringname,Integerage{}
System.out.println("ssss";
jdbcTemplate.update("insertintousersvalues(null,?,?;",name,age;


4.1.4App
ComponentScan(basePackages=".itmayiedu"EnableAutoConfigurationpublicclassApp{}
publicstaticvoidmain(String[]args{}
SpringApplication.run(App.class,args;

注意:spring-boot-starter-parent要在1.5以上
4.2springboot整合使用mybatis
4.2.1pom文件引入


<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId><version>1.3.2.RELEASEversion>
<relativePath/>
parent><dependencies>



<dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starterartifactId>
dependency><dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-testartifactId><scope>testscope>
dependency><dependency>
org.mybatis.spring.boot
mybatis-spring-boot-starter1.1.1
dependency><dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId><version>5.1.21version>
dependency><dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>


4.2.2、配置文件引入
spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=root
spring.datasource.driver-class-name=.mysql.jdbc.Driver

4.2.3Mapper代码
publicinterfaceUserMapper{
Select("SELECT*FROMUSERSWHERENAME=#{name}"UserfindByName(Param("name"Stringname;
Insert("INSERTINTOUSERS(NAME,AGEVALUES(#{name},#{age}"intinsert(Param("name"Stringname,Param("age"Integerage;

}

4.2.4、启动方式
ComponentScan(basePackages=".itmayiedu"MapperScan(basePackages=".itmayiedu.mapper"SpringBootApplicationpublicclassApp{}
publicstaticvoidmain(String[]args{}
SpringApplication.run(App.class,args;

4.3springboot整合使用springjpa
4.3.1pom文件引入依赖
<parent>

<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId><version>1.4.2.RELEASEversion>
parent><dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency><dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId><version>5.1.21version>
dependency><dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>


4.3.2创建User实体类
Entity(name="users"publicclassUser{
Id
GeneratedValueprivateIntegerid;Column
privateStringname;Column
privateIntegerage;
//..get/set方法}


4.3.3创建UserDao
publicinterfaceUserDaoextendsJpaRepository{}

4.3.4创建IndexController
RestController
publicclassIndexController{}
Autowired
privateUserDaouserDao;RequestMapping("/index"
publicStringindex(Integerid{
UserfindUser=userDao.findOne(id;System.out.println(findUser.getName(;return"success";

}
4.3.5启动项目
ComponentScan(basePackages={".itmayiedu"}
EnableJpaRepositories(basePackages=".itmayiedu.dao"EnableAutoConfiguration
EntityScan(basePackages=".itmayiedu.entity"

publicclassApp{}
publicstaticvoidmain(String[]args{
SpringApplication.run(App.class,args;

}

4.4springboot整合多数据源
同学们思考下,你们在项目中有使用到多数据源吗?
4.4.1配置文件中新增两个数据源
spring.datasource.test1.driverClassName=.mysql.jdbc.Driverspring.datasource.test1.url=
jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8spring.datasource.test1.username=rootspring.datasource.test1.password=root
spring.datasource.test2.driverClassName=.mysql.jdbc.Driverspring.datasource.test2.url=
jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8spring.datasource.test2.username=rootspring.datasource.test2.password=root

4.4.2配置文件中新增两个数据源
Configuration//注册到springboot容器中
MapperScan(basePackages=".itmayiedu.user1",sqlSessionFactoryRef="test1SqlSessionFactory"publicclassDataSource1Config{
/***
*methodDesc:功能描述:(配置test1数据库*author:余胜军*param:return

////
*createTime:2017917下午3:16:44*returnType:returnDataSource*copyright:每特教育科技*QQ:644064779*/
Bean(name="test1DataSource"Primary
ConfigurationProperties(prefix="spring.datasource.test1"publicDataSourcetestDataSource({}
returnDataSourceBuilder.create(.build(;
/***
*methodDesc:功能描述:(test1sql会话工厂*author:余胜军*param:param
*dataSource*param:return*param:throws*Exception
*createTime:2017917下午3:17:08*returnType:paramdataSource*returnType:return
*returnType:throwsExceptionSqlSessionFactory*copyright:每特教育科技*QQ:644064779*/
Bean(name="test1SqlSessionFactory"Primary
publicSqlSessionFactorytestSqlSessionFactory(Qualifier("test1DataSource"DataSourcedataSource

throwsException{
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean(;bean.setDataSource(dataSource;bean.setMapperLocations(

new
PathMatchingResourcePatternResolver(.getResources("classpath:mybatis/mapper/test1/*.xml";
/***
*methodDesc:功能描述:(test1事物管理*author:余胜军}
returnbean.getObject(;

}
*param:param
*dataSource*param:return*param:throws*Exception
*createTime:2017917下午3:17:08*returnType:paramdataSource*returnType:return
*returnType:throwsExceptionSqlSessionFactory*copyright:每特教育科技*QQ:644064779*/
Bean(name="test1TransactionManager"Primary
publicDataSourceTransactionManagertestTransactionManager(Qualifier("test1DataSource"DataSourcedataSource{}
returnnewDataSourceTransactionManager(dataSource;
Bean(name="test1SqlSessionTemplate"
publicSqlSessionTemplatetestSqlSessionTemplate(}

Qualifier("test1SqlSessionFactory"SqlSessionFactorysqlSessionFactorythrowsException{
returnnewSqlSessionTemplate(sqlSessionFactory;

4.4.2创建分包Mapper
publicinterfaceUser1Mapper{}
Insert("insertintousersvalues(null,#{name},#{age};"
publicintaddUser(Param("name"Stringname,Param("age"Integerage;
4.4.3启动项目
ComponentScan(basePackages=".itmayiedu"EnableAutoConfigurationpublicclassApp{
publicstaticvoidmain(String[]args{}
SpringApplication.run(App.class,args;

}


Noqualifyingbeanoftype
[javax.sql.DataSource]isdefined:expectedsinglematchingbeanbutfound2:test1DataSource,test2DataSource
五、物管理
5.1.1springboot整合事物管理
springboot默认集成事物,只主要在方法上加上Transactional即可
5.1.2SpringBoot分布式事物管理
使用springboot+jta+atomikos分布式事物管理
5.1.2.1新增配置文件信息
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jta-atomikosartifactId>
dependency>


5.1.2.2新增配置文件信息
#Mysql1
mysql.datasource.test.url=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8mysql.datasource.test.username=rootmysql.datasource.test.password=root

mysql.datasource.test.minPoolSize=3mysql.datasource.test.maxPoolSize=25mysql.datasource.test.maxLifetime=20000
mysql.datasource.test.borrowConnectionTimeout=30mysql.datasource.test.loginTimeout=30mysql.datasource.test.maintenanceInterval=60mysql.datasource.test.maxIdleTime=60mysql.datasource.test.testQuery=select1
#Mysql2
mysql.datasource.test2.url=jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8mysql.datasource.test2.username=rootmysql.datasource.test2.password=root
mysql.datasource.test2.minPoolSize=3mysql.datasource.test2.maxPoolSize=25mysql.datasource.test2.maxLifetime=20000
mysql.datasource.test2.borrowConnectionTimeout=30mysql.datasource.test2.loginTimeout=30mysql.datasource.test2.maintenanceInterval=60mysql.datasource.test2.maxIdleTime=60mysql.datasource.test2.testQuery=select1

5.1.2.3读取配置文件信息
package.itmayiedu.config;
importorg.springframework.boot.context.properties.ConfigurationProperties;
ConfigurationProperties(prefix="mysql.datasource.test"publicclassDBConfig1{
privateStringurl;privateStringusername;privateStringpassword;privateintminPoolSize;privateintmaxPoolSize;privateintmaxLifetime;
privateintborrowConnectionTimeout;privateintloginTimeout;

}
privateintmaintenanceInterval;privateintmaxIdleTime;privateStringtestQuery;
package.itmayiedu.config;
importorg.springframework.boot.context.properties.ConfigurationProperties;
ConfigurationProperties(prefix="mysql.datasource.test1"publicclassDBConfig2{}
privateStringurl;privateStringusername;privateStringpassword;privateintminPoolSize;privateintmaxPoolSize;privateintmaxLifetime;
privateintborrowConnectionTimeout;privateintloginTimeout;privateintmaintenanceInterval;privateintmaxIdleTime;

privateStringtestQuery;


5.1.2.4创建多数据源
Configuration
//basePackages最好分开配置如果放在同一个文件夹可能会报错
MapperScan(basePackages=".itmayiedu.test01",sqlSessionTemplateRef="testSqlSessionTemplate"publicclassTestMyBatisConfig1{
//配置数据源Primary
Bean(name="testDataSource"
publicDataSourcetestDataSource(DBConfig1testConfigthrowsSQLException{
MysqlXADataSourcemysqlXaDataSource=newMysqlXADataSource(;mysqlXaDataSource.setUrl(testConfig.getUrl(;
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true;

}

mysqlXaDataSource.setPassword(testConfig.getPassword(;mysqlXaDataSource.setUser(testConfig.getUsername(;mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true;

AtomikosDataSourceBeanxaDataSource=newAtomikosDataSourceBean(;xaDataSource.setXaDataSource(mysqlXaDataSource;xaDataSource.setUniqueResourceName("testDataSource";
}
xaDataSource.setMinPoolSize(testConfig.getMinPoolSize(;xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize(;xaDataSource.setMaxLifetime(testConfig.getMaxLifetime(;
xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout(;xaDataSource.setLoginTimeout(testConfig.getLoginTimeout(;
xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval(;xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime(;xaDataSource.setTestQuery(testConfig.getTestQuery(;returnxaDataSource;
Bean(name="testSqlSessionFactory"
publicSqlSessionFactorytestSqlSessionFactory(Qualifier("testDataSource"DataSourcedataSource}

throwsException{
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean(;bean.setDataSource(dataSource;returnbean.getObject(;
Bean(name="testSqlSessionTemplate"
publicSqlSessionTemplatetestSqlSessionTemplate(}

Qualifier("testSqlSessionFactory"SqlSessionFactorysqlSessionFactorythrowsException{
returnnewSqlSessionTemplate(sqlSessionFactory;
package.itmayiedu.datasource;
importjava.sql.SQLException;
importjavax.sql.DataSource;
importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.mybatis.spring.SqlSessionTemplate;importorg.mybatis.spring.annotation.MapperScan;

importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;import.atomikos.jdbc.AtomikosDataSourceBean;import.itmayiedu.config.DBConfig1;
import.mysql.jdbc.jdbc2.optional.MysqlXADataSource;
Configuration
//basePackages最好分开配置如果放在同一个文件夹可能会报错
MapperScan(basePackages=".itmayiedu.test02",sqlSessionTemplateRef="test2SqlSessionTemplate"publicclassTestMyBatisConfig2{
Bean(name="test2SqlSessionFactory"
publicSqlSessionFactorytestSqlSessionFactory(Qualifier("test2DataSource"DataSourcedataSource}

throwsException{
}
xaDataSource.setMinPoolSize(testConfig.getMinPoolSize(;xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize(;xaDataSource.setMaxLifetime(testConfig.getMaxLifetime(;
xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout(;xaDataSource.setLoginTimeout(testConfig.getLoginTimeout(;
xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval(;xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime(;xaDataSource.setTestQuery(testConfig.getTestQuery(;returnxaDataSource;

AtomikosDataSourceBeanxaDataSource=newAtomikosDataSourceBean(;xaDataSource.setXaDataSource(mysqlXaDataSource;xaDataSource.setUniqueResourceName("test2DataSource";
//配置数据源
Bean(name="test2DataSource"
publicDataSourcetestDataSource(DBConfig1testConfigthrowsSQLException{
MysqlXADataSourcemysqlXaDataSource=newMysqlXADataSource(;mysqlXaDataSource.setUrl(testConfig.getUrl(;
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true;mysqlXaDataSource.setPassword(testConfig.getPassword(;mysqlXaDataSource.setUser(testConfig.getUsername(;mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true;
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean(;bean.setDataSource(dataSource;returnbean.getObject(;

}
Bean(name="test2SqlSessionTemplate"
publicSqlSessionTemplatetestSqlSessionTemplate(}

Qualifier("test2SqlSessionFactory"SqlSessionFactorysqlSessionFactorythrowsException{
returnnewSqlSessionTemplate(sqlSessionFactory;


5.1.2.4启动加载配置
EnableConfigurationProperties(value={DBConfig1.class,DBConfig2.class}


六、志管理
6.1使用log4j记录日志
6.1.2新建log4j配置文件
#log4j.rootLogger=CONSOLE,info,error,DEBUGlog4j.rootLogger=info,error,CONSOLE,DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm}[%t][%c][%p]-%m%nlog4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm}[%t][%c][%p]-%m%nlog4j.appender.info.datePattern='.'yyyy-MM-ddlog4j.appender.info.Threshold=infolog4j.appender.info.append=true
#log4j.appender.info.File=/home/admin/pms-api-services/logs/info/api_services_info
log4j.appender.info.File=/Users/dddd/Documents/testspace/pms-api-services/logs/info/api_services_infolog4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm}[%t][%c][%p]-%m%nlog4j.appender.error.datePattern='.'yyyy-MM-dd

log4j.appender.error.Threshold=errorlog4j.appender.error.append=true
#log4j.appender.error.File=/home/admin/pms-api-services/logs/error/api_services_error
log4j.appender.error.File=/Users/dddd/Documents/testspace/pms-api-services/logs/error/api_services_errorlog4j.logger.DEBUG=DEBUG
log4j.appender.DEBUG=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm}[%t][%c][%p]-%m%nlog4j.appender.DEBUG.datePattern='.'yyyy-MM-ddlog4j.appender.DEBUG.Threshold=DEBUGlog4j.appender.DEBUG.append=true
#log4j.appender.DEBUG.File=/home/admin/pms-api-services/logs/debug/api_services_debug
log4j.appender.DEBUG.File=/Users/dddd/Documents/testspace/pms-api-services/logs/debug/api_services_debug


6.2使用AOP统一处理Web请求日志
6.2.1POM文件新增依赖

<dependency>

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

6.2.2POM文件新增依赖
AspectComponent
publicclassWebLogAspect{
privateLoggerlogger=LoggerFactory.getLogger(getClass(;Pointcut("execution(public*.itmayiedu.controller..*.*(.."publicvoidwebLog({}
Before("webLog("
publicvoiddoBefore(JoinPointjoinPointthrowsThrowable{
//接收到请求,记录请求容
ServletRequestAttributesattributes=(ServletRequestAttributes
RequestContextHolder.getRequestAttributes(;

HttpServletRequestrequest=attributes.getRequest(;

}
}
//记录下请求容
logger.info("URL:"+request.getRequestURL(.toString(;logger.info("HTTP_METHOD:"+request.getMethod(;logger.info("IP:"+request.getRemoteAddr(;Enumerationenu=request.getParameterNames(;while(enu.hasMoreElements({}
Stringname=(Stringenu.nextElement(;
logger.info("name:{},value:{}",name,request.getParameter(name;
AfterReturning(returning="ret",pointcut="webLog("publicvoiddoAfterReturning(ObjectretthrowsThrowable{}
//处理完请求,返回容
logger.info("RESPONSE:"+ret;


七、存支持
7.1注解配置与EhCache使用
7.1.1pom文件引入
<dependency>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-cacheartifactId>dependency>


7.1.2新建ehcache.xml文件
xmlversion="1.0"encoding="UTF-8"?>
<ehcachexmlns:xsi=".w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="ehcache.org/ehcache.xsd"updateCheck="false">
<diskStorepath="java.io.tmpdir/Tmp_EhCache"/>


<defaultCachemaxElementsInMemory="5000"eternal="false"
timeToIdleSeconds="120"timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU"overflowToDisk="false"/>
<cachename="baseCache"maxElementsInMemory="10000"
maxElementsOnDisk="100000"/>
ehcache>
配置信息介绍
1.2.3.4.5.6.

10.diskPersistent:是否缓存虚拟机重启期数


7.1.3代码使用Cacheable
CacheConfig(cacheNames="baseCache"publicinterfaceUserMapper{
Select("select*fromuserswherename=#{name}"Cacheable

}
UserEntityfindName(Param("name"Stringname;

7.1.4清除缓存
Autowired
privateCacheManagercacheManager;RequestMapping("/remoKey"publicvoidremoKey({}
cacheManager.getCache("baseCache".clear(;

使用Redis做集中式缓存

八、他容

8.1、使用Scheduled创建定时任务
SpringBoot的主类中加入EnableScheduling注解,启用定时任务的配置
Component
publicclassScheduledTasks{
privatestaticfinalSimpleDateFormatdateFormat=newSimpleDateFormat("HH:mm:ss";Scheduled(fixedRate=5000
publicvoidreportCurrentTime({
System.out.println("现在时间:"+dateFormat.format(newDate(;}}


8.2、使用Async实现异步调用
启动加上EnableAsync,需要执行异步方法上加入Async
8.3、自定义参数
配置文件值name=itmayiedu.
配置文件值

Value("${name}"privateStringname;
ResponseBody
RequestMapping("/getValue"publicStringgetValue({}
returnname;


8.4、多环境配置
spring.profiles.active=pre
application-dev.properties:开发环境application-test.properties:测试环境application-prod.properties:生产环境
8.5、修改端口号
server.port=8888
server.context-path=/itmayiedu
8.6SpringBootyml使用
创建application.yml

server:port:8090
context-path:/itmayiedu


8.7、发布打包
使用mvnclean清除以前的编译文件使用mvnpackage打包使用javajar包名
如果报错没有主清单,pom文件中新增


<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId><artifactId>maven-compiler-pluginartifactId><configuration>
<source>1.8source><target>1.8target>
configuration>
plugin><plugin>
<groupId>org.springframework.bootgroupId><artifactId>spring-boot-maven-pluginartifactId><configuration>
<maimClass>.itmayiedu.app.AppmaimClass>configuration><executions>
<execution>
<goals>
<goal>repackagegoal>goals>
execution>
executions>
plugin>
plugins>
build>






本文来源:https://www.2haoxitong.net/k/doc/e37cde04250c844769eae009581b6bd97f19bca0.html

《SpringBoot学习资料.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式