SpringBoot总结-基于SpringBoot实现Web开发

原创作者:田超凡(程序员田宝宝)

版权所有,转载请注明原作者,严禁复制转载

3.1、静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。

默认配置

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

/static

/public

/resources

/META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。

3.2、渲染Web页面

Com.tcf.controller---视图层 渲染我们页面

Com.tcf.service---业务逻辑层

Com.tcf.dao---数据库访问层

前后端

渲染Web页面

在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

模板引擎 能够非常好的帮助seo搜索到该网页

在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。

Spring Boot提供了默认配置的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

3.3 YML与Properties用法

SpringBoot支持两种配置方式,一种是properties文件,一种是yml。

使用yml可以减少配置文件的重复性。

例如:application.properties配置

|--------------------------------|
| tcf.name=tcftcf.age=22 |

例如:application.yml配置

在企业中application.yml方式用的是比较多的;

3.4、使用Freemarker模板引擎渲染web视图

3.4.1、pom文件引入:

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <!-- 引入freeMarker的依赖包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-++freemarker++</artifactId> </dependency> |

3.4.2、后台代码

在src/main/resources/创建一个templates文件夹,后缀为*.ftl

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @RequestMapping ( "/index" ) public String index(Map<String, Object> map ) { map .put( "name" , "XXX" ); return "index" ; } |

3.4.3、前台代码

|---------------------------------------------------------------------------------------------------------------------------------------------|
| <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> ${name} </body> </html> |

3.4.4、Freemarker其他用法

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @RequestMapping("/freemarkerIndex") public String index(Map<String, Object> result) { result.put("name", "zhangsan"); result.put("sex", "0"); List<String> listResult = new ArrayList<String>(); listResult.add("zhangsan"); listResult.add("lisi"); listResult.add("tcf"); result.put("listResult", listResult); return "index"; } <!DOCTYPE ++html++> ++<html>++ <head ++lang++ ="++en++"> <meta ++charset++="UTF-8" /> <title> 首页 </title> </head> <body> {name}** **\<#if sex=="1"\>** **男** **\<#++elseif++ sex=="2"\>** **女** **\<#else\>** **其他** **\** **\<#list ++userlist++ as user\>** **{user} </#list> </body> ++</html>++ |

复制代码
两种方法 

1 用符号代替: > gt , >=  gte  ,< lt  , <= lte

2 加括号 <#if(x>y)>

3.4.4、Freemarker配置

新建application.yml文件

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| spring: http: encoding: force: true###模版引擎编码为UTF-8charset: UTF-8 freemarker: allow-request-override: false cache: false check-template-location: true charset: UTF-8 content-type: text/html; charset=utf-8 expose-request-attributes: false expose-session-attributes: false expose-spring-macro-helpers: false##模版文件结尾.ftlsuffix: .ftl ##模版文件目录template-loader-path: classpath:/templates |

3.5使用thymeleaf渲染Web页面

3.5.1什么是thymeleaf

thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。

3.5.2 Maven依赖

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| \<!--Spring SpringMVC --\><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> \<!--引入thymeleaf的依赖--\><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |

3.5.3 配置文件新增

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| ###ThymeLeaf配置spring: thymeleaf: #prefix:指定模板所在的目录prefix: classpath:/templates/ #check-tempate-location:检查模板路径是否存在check-template-location: true#cache:是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。cache: true suffix: .html encoding: UTF-8 mode: HTML5 |

3.5.4 案例代码

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| importcom.tcf.entity.UserEntity; importorg.springframework.stereotype.Controller; importorg.springframework.web.bind.annotation.RequestMapping; importjava.util.Map; @Controller public classIndexController { @RequestMapping("/myThymeleaf") publicString myThymeleaf(Map<String, Object> result) { result.put("user", newUserEntity("tcf", 22)); return"myThymeleaf"; } } public classUserEntity { privateString userName; privateInteger age; publicUserEntity(String userName, Integer age) { this.userName= userName; this.age= age; } publicString getUserName() { returnuserName; } publicInteger getAge() { returnage; } public voidsetUserName(String userName) { this.userName= userName; } public voidsetAge(Integer age) { this.age= age; } } <!DOCTYPE html> \<!--需要在HTML文件中加入以下语句:--\><htmllang="en"xmlns:th="http://www.thymeleaf.org"> <head> <metacharset="UTF-8"> <title>Show User</title> </head> <body> <table> 姓名:<spanth:text="${user.userName}"></span> 年龄:<spanth:text="${user.age}"></span> </table> </body> </html> |

3.5.4 高级写法

循环语句:

|------------------------------------------------------------------------------------------------------------------------------|
| <ulth:each="user:${userList}"> <lith:text="${user.userName}"></li> <lith:text="${user.age}"></li> <br> </ul> |

If判断:

复制代码
<spanth:if="${user.age\>17}">已经成年啦</span>

<spanth:if="${user.age\<17}">未成年</span>

详细可以更多语法可以查看https://www.thymeleaf.org/documentation.html

  • 数据库访问

4.1、springboot整合使用JdbcTemplate

4.1.1 pom文件引入

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE </version> </parent> < dependencies > < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-++jdbc++ </ artifactId > </ dependency > < dependency > < groupId > ++mysql++ </ groupId > < artifactId > ++mysql++ -connector-java </ artifactId > ++<++ ++version++ ++>++ ++5.1.21++ ++</++ ++version++ ++>++ </ dependency > < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-test </ artifactId > < scope > test </ scope > </ dependency > < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-web </ artifactId > </ dependency > </ dependencies > |

4.1.2 application.yml新增配置

|------------------------------------------------------------------------------------------------------------------------------------------|
| spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root driver-class-name: com.mysql.jdbc.Driver |

4.1.3 UserService类

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Service public classUserServiceImpl implementsUserService { @Autowired privateJdbcTemplate jdbcTemplate; @Override publicBoolean inserUser(String name, Integer age) { intupdate = jdbcTemplate.update("insert into users values(null,?,?);", name, age); returnupdate > 0 ? true: false; } } |

4.1.4 App类

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @ComponentScan (basePackages = "com.tcf" ) @EnableAutoConfiguration public class App { public static void main(String[] args ) { SpringApplication.run(App. class , args ); } } |

4.1.5数据库表结构

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL COMMENT '用户名称', `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; |

4.2、springboot整合使用mybatis

4.2.1、pom文件引入

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> \<!-- springboot整合mybatis --\><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies> |

4.2.2、application.yml

|------------------------------------------------------------------------------------------------------------------------------------------|
| spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root driver-class-name: com.mysql.jdbc.Driver |

4.2.3、Mapper代码

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| public interface UserMapper { @Select ( "SELECT * FROM USERS WHERE NAME = #{name}" ) User findByName( @Param ( "name" ) String name ); @Insert ( "INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})" ) int insert( @Param ( "name" ) String name , @Param ( "age" ) Integer age ); } |

4.2.4、启动方式

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @SpringBootApplication @MapperScan("com.tcf.mapper") public classAppMybatis { public static voidmain(String[] args) { SpringApplication.run(AppMybatis.class); } } |

4、springboot整合多数据源

同学们思考下,你们在项目中有使用到多数据源吗?

4.4.1配置文件中新增两个数据源

application.yml

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| spring: datasource: ###会员数据库member: jdbc-url: jdbc:mysql://localhost:3306/user username: root password: root driver-class-name: com.mysql.jdbc.Driver ###订单数据库order: jdbc-url: jdbc:mysql://localhost:3306/order username: root password: root driver-class-name: com.mysql.jdbc.Driver |

备注:如果是SpringBoot2配置多数据源 ,报如下错误:

"jdbcUrl is required with driverClassName."或者Cause: java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.] with root cause

解决方案:

spring.datasource.url 和spring.datasource.driverClassName,换成

spring.datasource.jdbc-url和spring.datasource.driver-class-name

4.4.2数据库数据源相关配置
会员数据源

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Configuration @MapperScan(basePackages = "com.tcf.member.mapper", sqlSessionFactoryRef = "memberSqlSessionFactory") public classMemberDataSourceConfig { /\*\* \*将会员db注册到容器中\* \* **@return**\*/@Bean(name = "memberDataSource") @ConfigurationProperties(prefix = "spring.datasource.member") publicDataSource memberDataSource() { returnDataSourceBuilder.create().build(); } /\*\* \*将会员SqlSessionFactory注册到容器中\* \* **@param***dataSource*\* **@return** \* **@throws**Exception \*/@Bean(name = "memberSqlSessionFactory") publicSqlSessionFactory memberSqlSessionFactory(@Qualifier("memberDataSource") DataSource dataSource) throwsException { SqlSessionFactoryBean sqlSessionFactoryBean = newSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(memberDataSource()); returnsqlSessionFactoryBean.getObject(); } /\*\* \*创建会员管理器\* \* **@param***dataSource*\* **@return**\*/@Bean(name = "memberTransactionManager") publicDataSourceTransactionManager memberTransactionManager(@Qualifier("memberDataSource") DataSource dataSource) { return newDataSourceTransactionManager(dataSource); } /\*\* \*创建订单sqlSesion模版\* \* **@param***sqlSessionFactory*\* **@return** \* **@throws**Exception \*/@Bean(name = "memberSqlSessionTemplate") publicSqlSessionTemplate menberSqlSessionTemplate( @Qualifier("memberSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException { return newSqlSessionTemplate(sqlSessionFactory); } } |

订单数据源

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Configuration @MapperScan(basePackages = "com.tcf.order.mapper", sqlSessionFactoryRef = "orderSqlSessionFactory") public classOrderDataSourceConfig { /\*\* \*将订单db注册到容器中\* \* **@return**\*/@Bean(name = "orderDataSource") @ConfigurationProperties(prefix = "spring.datasource.order") publicDataSource orderDataSource() { returnDataSourceBuilder.create().build(); } /\*\* \*将订单SqlSessionFactory注册到容器中\* \* **@param***dataSource*\* **@return** \* **@throws**Exception \*/@Bean(name = "orderSqlSessionFactory") publicSqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throwsException { SqlSessionFactoryBean sqlSessionFactoryBean = newSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(orderDataSource()); returnsqlSessionFactoryBean.getObject(); } /\*\* \*创建订单管理器\* \* **@param***dataSource*\* **@return**\*/@Bean(name = "orderTransactionManager") publicDataSourceTransactionManager orderTransactionManager(@Qualifier("orderDataSource") DataSource dataSource) { return newDataSourceTransactionManager(dataSource); } /\*\* \*创建订单sqlSesion模版\* \* **@param***sqlSessionFactory*\* **@return** \* **@throws**Exception \*/@Bean(name = "orderSqlSessionTemplate") publicSqlSessionTemplate menberSqlSessionTemplate( @Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException { return newSqlSessionTemplate(sqlSessionFactory); } } |

4.4.2创建分包Mapper
会员mapper

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| public interfaceMemberMapper { @Insert("insert into users values(null,#{name},#{age});") public intaddUser(@Param("name") String name, @Param("age") Integer age); } |

订单mapper

|----------------------------------------------------------------------------------------------------------------------------------------------------|
| public interfaceOrderMapper { @Insert("insert into order_number values(null,#{number});") intinserOrder(@Param("number") String number); } |

4.4.3启动项目

|----------------------------------------------------------------------------------------------------------------------------------------------------|
| @SpringBootApplication public classAppSpringBoot { public static voidmain(String[] args) { SpringApplication.run(AppSpringBoot.class); } } |

4.4.4Maven相关依赖

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.8.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> \<!-- springboot整合mybatis --\><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> </dependencies> |

4.4.5 数据库表结构

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL COMMENT '用户名称', `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `order_number` ( `id` int(11) NOT NULL AUTO_INCREMENT, `order_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; |

  • 事务管理

5.1.1Springboot整合事务管理

springboot默认集成事务,只主要在方法上加上@Transactional即可

5.1.2SpringBoot分布式事务管理

使用springboot+jta+atomikos 分布式事物Transactional管理

5.1.2.1 多数据源分布式事务案例

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Service public classMemberService { @Autowired privateMemberMapper memberMapper; @Autowired privateOrderMapper orderMapper; @Transactional(transactionManager = "memberTransactionManager") public intaddUser(String userName, Integer age) { intresult = memberMapper.addUser(userName, age); orderMapper.inserOrder(userName); intj = 1 / age; returnresult; } } |

5.1.2.1新增配置文件信息

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| < dependency > < groupId > org.springframework.boot </ groupId > < artifactId > spring-boot-starter-++jta++ -++atomikos++ </ artifactId > </ dependency > |

5.1.2.2新增配置文件信息

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| spring: datasource: ###用户数据库member: url: jdbc:mysql://localhost:3306/user username: root password: root borrowConnectionTimeout: 30 loginTimeout: 30 maintenanceInterval: 60 maxIdleTime: 60 maxLifetime: 20000 maxPoolSize: 25 minPoolSize: 3 uniqueResourceName: orderDatasource ###订单数据库order: url: jdbc:mysql://localhost:3306/order username: root password: root borrowConnectionTimeout: 30 loginTimeout: 30 maintenanceInterval: 60 maxIdleTime: 60 maxLifetime: 20000 maxPoolSize: 25 minPoolSize: 3 uniqueResourceName: memberDatasource |

5.1.2.3 读取配置文件信息

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @ConfigurationProperties(prefix = "spring.datasource.member") @Data public classMemberConfig { privateString url; privateString userName; privateString passWord; private intminPoolSize; private intmaxPoolSize; private intmaxLifetime; private intborrowConnectionTimeout; private intloginTimeout; private intmaintenanceInterval; private intmaxIdleTime; privateString testQuery; privateString uniqueResourceName; } @ConfigurationProperties(prefix = "spring.datasource.order") @Data public classOrderConfig { privateString url; privateString userName; privateString passWord; private intminPoolSize; private intmaxPoolSize; private intmaxLifetime; private intborrowConnectionTimeout; private intloginTimeout; private intmaintenanceInterval; private intmaxIdleTime; privateString testQuery; privateString uniqueResourceName; } |

5.1.2.4 创建多数据源

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Configuration @MapperScan(basePackages = "com.tcf.member.mapper", sqlSessionTemplateRef = "memberSqlSessionTemplate") public classMemberDataSourceConfig { //@Configuration xml MemberDataSourceConfig.xml /\*\* \*创建我们的DataSource \* \* **@return**\*/@Bean("memberDataSource") publicDataSource memberDataSource(MemberConfig memberConfig) throwsSQLException { // 1.创建MysqlXADataSourceMysqlXADataSource mysqlXaDataSource = newMysqlXADataSource(); mysqlXaDataSource.setUrl(memberConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(memberConfig.getPassWord()); mysqlXaDataSource.setUser(memberConfig.getUserName()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); // 2.将本地事务注册到创Atomikos全局事务AtomikosDataSourceBean xaDataSource = newAtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName(memberConfig.getUniqueResourceName()); xaDataSource.setMinPoolSize(memberConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(memberConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(memberConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(memberConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(memberConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(memberConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(memberConfig.getMaxIdleTime()); xaDataSource.setTestQuery(memberConfig.getTestQuery()); returnxaDataSource; } /\*\* \*创建我们的SqlSessionFactory \* \* **@param***dataSource*\* **@return** \* **@throws**Exception \*/@Bean(name = "memberSqlSessionFactory") publicSqlSessionFactory memberSqlSessionFactory(@Qualifier("memberDataSource") DataSource dataSource) throwsException { SqlSessionFactoryBean sqlSessionFactoryBean = newSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); returnsqlSessionFactoryBean.getObject(); } /\*\* \*创建订单sqlSesion模版\* \* **@param***sqlSessionFactory*\* **@return** \* **@throws**Exception \*/@Bean(name = "memberSqlSessionTemplate") publicSqlSessionTemplate memberSqlSessionTemplate( @Qualifier("memberSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException { return newSqlSessionTemplate(sqlSessionFactory); } } @Configuration @MapperScan(basePackages = "com.tcf.order.mapper", sqlSessionTemplateRef = "orderSqlSessionTemplate") public classOrderDataSourceConfig { //@Configuration xml orderDataSourceConfig.xml /\*\* \*创建我们的DataSource \* \* **@return**\*/@Bean("orderDataSource") publicDataSource orderDataSource(OrderConfig orderConfig) throwsSQLException { // 1.创建MysqlXADataSourceMysqlXADataSource mysqlXaDataSource = newMysqlXADataSource(); mysqlXaDataSource.setUrl(orderConfig.getUrl()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); mysqlXaDataSource.setPassword(orderConfig.getPassWord()); mysqlXaDataSource.setUser(orderConfig.getUserName()); mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); // 2.将本地事务注册到创Atomikos全局事务AtomikosDataSourceBean xaDataSource = newAtomikosDataSourceBean(); xaDataSource.setXaDataSource(mysqlXaDataSource); xaDataSource.setUniqueResourceName(orderConfig.getUniqueResourceName()); xaDataSource.setMinPoolSize(orderConfig.getMinPoolSize()); xaDataSource.setMaxPoolSize(orderConfig.getMaxPoolSize()); xaDataSource.setMaxLifetime(orderConfig.getMaxLifetime()); xaDataSource.setBorrowConnectionTimeout(orderConfig.getBorrowConnectionTimeout()); xaDataSource.setLoginTimeout(orderConfig.getLoginTimeout()); xaDataSource.setMaintenanceInterval(orderConfig.getMaintenanceInterval()); xaDataSource.setMaxIdleTime(orderConfig.getMaxIdleTime()); xaDataSource.setTestQuery(orderConfig.getTestQuery()); returnxaDataSource; } /\*\* \*创建我们的SqlSessionFactory \* \* **@param***dataSource*\* **@return** \* **@throws**Exception \*/@Bean(name = "orderSqlSessionFactory") publicSqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throwsException { SqlSessionFactoryBean sqlSessionFactoryBean = newSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); returnsqlSessionFactoryBean.getObject(); } // // /\*\* // \*创建会员管理器// \* // \* @param dataSource // \* @return // \*/ // @Bean(name = "orderTransactionManager") // public DataSourceTransactionManager orderTransactionManager(@Qualifier("orderDataSource") DataSource dataSource) { // return new DataSourceTransactionManager(dataSource); // } /\*\* \*创建订单sqlSesion模版\* \* **@param***sqlSessionFactory*\* **@return** \* **@throws**Exception \*/@Bean(name = "orderSqlSessionTemplate") publicSqlSessionTemplate orderSqlSessionTemplate( @Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException { return newSqlSessionTemplate(sqlSessionFactory); } } |

如果多数据源使用事务报错的话

cted single matching bean but found 2: memberTransactionManager,orderTransactionManager

@Transactional(transactionManager = "memberTransactionManager")

明确指定使用那个事务管理器即可

5.1.2.4 启动加载配置
复制代码
@EnableConfigurationProperties({OrderConfig.class, MemberConfig.class})
  • 整合热部署

6.1、Spring Boot集成lombok让代码更简洁

1.需要安装Idea整合 整合Lombok插件,

  1. 搜索Lombok插件即可
  1. 点击 install 然后,安装成功之后,点击 重启 idea 即可。

整合 lombok 注意事项

  1. 需要在 idea 中安装 lombok 插件; ----- 没有做
  2. 引入到 lombok 依赖;

加上了注解,根本就没有生成 get set 方法。

原理:

实际上在开发写代码的时候 是不需要写 get set 方法,但是在编译 class 文件中,帮你自动生成好这样 get set 方法 放入到 class 文件中。

6.1.2添加lombok依赖

|------------------------------------------------------------------------------------------------------------------|
| <dependency> <groupId>org.projectlombok</groupId> <artifactId>++lombok++ </artifactId> </dependency> |

6.1.3实体类演示

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Slf4j @Data public class UserEntity { // @Getter // @Setter private String userName; // @Getter // @Setter private Integer age; @Override public String toString() { return "UserEntity [userName=" + userName + ", age=" + age + "]"; } public static void main(String[] args) { UserEntity userEntity = new UserEntity(); userEntity.setUserName("zhangsan"); userEntity.setAge(20); System.out .println(userEntity.toString()); log .info("####我是日志##########"); } } |

6.1.4其他特性

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Data 标签,生成getter/setter toString()等方法 @NonNull : 让你不在担忧并且爱上NullPointerException @CleanUp : 自动资源管理:不用再在finally中添加资源的close方法 @Setter/@Getter : 自动生成set和get方法 @ToString : 自动生成toString方法 @EqualsAndHashcode : 从对象的字段中生成hashCode和equals的实现 @NoArgsConstructor/@RequiredArgsConstructor/@AllArgsConstructor 自动生成构造方法 @Data : 自动生成set/get方法,toString方法,equals方法,hashCode方法,不带参数的构造方法 @Value : 用于注解final类 @Builder : 产生复杂的构建器api类 @SneakyThrows : 异常处理(谨慎使用) @Synchronized : 同步方法安全的转化 @Getter(lazy=true) : @Log : 支持各种logger对象,使用时用对应的注解,如:@Log4 |

6.1.5 打印日志
复制代码
private staticLogger log= Logger.getLogger(App.class);
复制代码
直接在类上加上@Slf4j 

6.2、Spring Boot整合热部署框架

6.2.1什么是热部署

修改java类或页面或者静态文件,不需要手动重启

原理:类加载器

适合于本地开发环境

6.2.1 Maven依赖

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| \<!--SpringBoot热部署配置--\><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> |

6.3.3 Idea工具设置
  1. "File" -> "Settings" -> "Build,Execution,Deplyment" -> "Compiler",选中打勾 "Build project automatically" 。

2) 组合键:"Shift+Ctrl+Alt+/" ,选择 "Registry" ,选中打勾 "compiler.automake.allow.when.app.running"

6.3.4效果演示

按住保存键,自动帮我实现重启

本文部分素材转载自蚂蚁课堂

相关推荐
惊讶的猫19 分钟前
nia500总结
java·spring·mybatis
奔跑吧 android29 分钟前
【ubuntu24.04】【安装jdk】
java·开发语言
BUTCHER542 分钟前
Java 启动服务时指定JVM(Java 虚拟机)的参数配置说明
java·开发语言·jvm
sheji34161 小时前
【开题答辩全过程】以 会议室场地预约系统为例,包含答辩的问题和答案
java
摇滚侠1 小时前
尚硅谷 Java 零基础全套视频教程,System、Runtime、BigDecimal、BigInteger、Random,笔记 151
java·开发语言·笔记
fo安方1 小时前
软考~系统规划与管理师考试——真题篇——章节——第5章 应用系统规划——解析版
java·运维·网络
阿杰真不会敲代码1 小时前
POI 讲解
java·spring boot
海鸥811 小时前
ArgoCD App of Apps 模式详解
java·elasticsearch·argocd
二哈喇子!1 小时前
面向对象经典题整理
java·面向对象·
二哈喇子!1 小时前
模仿淘宝购物系统的Java Web前端项目(开源项目)
java·javaweb