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>

        其他     

       

        </#if>     

       <#list userlist as user>

         ${user}

       </#list>

</body>

</html>

两种方法 1 用符号代替: > gt , >=  gte  ,< lt  , <= lte2 加括号 <#if(x>y)>

3.4.4、Freemarker配置

新建application.yml文件

spring:http:encoding:force: true### 模版引擎编码为UTF-8charset: UTF-8freemarker:allow-request-override: falsecache: falsecheck-template-location: truecharset: UTF-8content-type: text/html; charset=utf-8expose-request-attributes: falseexpose-session-attributes: falseexpose-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: truesuffix:  .htmlencoding: UTF-8mode: HTML5

 3.5.4 案例代码

import com.tcf.entity.UserEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import java.util.Map;
@Controllerpublic class IndexController {@RequestMapping("/myThymeleaf")public String myThymeleaf(Map<String, Object> result) {result.put("user", new UserEntity("tcf", 22));return "myThymeleaf";}}
 

public class UserEntity {private String userName;private Integer age;public UserEntity(String userName, Integer age) {this.userName = userName;this.age = age;}public String getUserName() {return userName;}public Integer getAge() {return age;}public void setUserName(String userName) {this.userName = userName;}public void setAge(Integer age) {this.age = age;}}
 

<!DOCTYPE html><!--需要在HTML文件中加入以下语句: --><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Show User</title></head><body><table>姓名:<span th:text="${user.userName}"></span>年龄:<span th:text="${user.age}"></span></table></body></html>

 3.5.4 高级写法

循环语句:

<ul th:each="user:${userList}"><li th:text="${user.userName}"></li><li th:text="${user.age}"></li><br></ul>
 

If判断:

<span th:if="${user.age>17}">已经成年啦</span><span th: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/testusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver

4.1.3 UserService类
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic Boolean inserUser(String name, Integer age) {int update = jdbcTemplate.update("insert into users values(null,?,?);", name, age);return update > 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/testusername: rootpassword: rootdriver-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 class AppMybatis {public static void main(String[] args) {SpringApplication.run(AppMybatis.class);}}

4、springboot整合多数据源

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

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

application.yml

spring:datasource:###会员数据库member:jdbc-url: jdbc:mysql://localhost:3306/userusername: rootpassword: rootdriver-class-name: com.mysql.jdbc.Driver###订单数据库order:jdbc-url: jdbc:mysql://localhost:3306/orderusername: rootpassword: rootdriver-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 class MemberDataSourceConfig {/*** 将会员db注册到容器中** @return*/@Bean(name = "memberDataSource")@ConfigurationProperties(prefix = "spring.datasource.member")public DataSource memberDataSource() {return DataSourceBuilder.create().build();}/*** 将会员SqlSessionFactory注册到容器中** @param dataSource* @return* @throws Exception*/@Bean(name = "memberSqlSessionFactory")public SqlSessionFactory memberSqlSessionFactory(@Qualifier("memberDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(memberDataSource());return sqlSessionFactoryBean.getObject();}/*** 创建会员管理器** @param dataSource* @return*/@Bean(name = "memberTransactionManager")public DataSourceTransactionManager memberTransactionManager(@Qualifier("memberDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}/*** 创建订单sqlSesion模版** @param sqlSessionFactory* @return* @throws Exception*/@Bean(name = "memberSqlSessionTemplate")public SqlSessionTemplate menberSqlSessionTemplate(@Qualifier("memberSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}

订单数据源

@Configuration@MapperScan(basePackages = "com.tcf.order.mapper", sqlSessionFactoryRef = "orderSqlSessionFactory")public class OrderDataSourceConfig {/*** 将订单db注册到容器中** @return*/@Bean(name = "orderDataSource")@ConfigurationProperties(prefix = "spring.datasource.order")public DataSource orderDataSource() {return DataSourceBuilder.create().build();}/*** 将订单SqlSessionFactory注册到容器中** @param dataSource* @return* @throws Exception*/@Bean(name = "orderSqlSessionFactory")public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(orderDataSource());return sqlSessionFactoryBean.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")public SqlSessionTemplate menberSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}

4.4.2创建分包Mapper

会员mapper
public interface MemberMapper {@Insert("insert into users values(null,#{name},#{age});")public int addUser(@Param("name") String name, @Param("age") Integer age);}

订单mapper
public interface OrderMapper {@Insert("insert into order_number values(null,#{number});")int inserOrder(@Param("number") String number);}

4.4.3启动项目
@SpringBootApplicationpublic class AppSpringBoot {public static void main(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 多数据源分布式事务案例
@Servicepublic class MemberService {@Autowiredprivate MemberMapper memberMapper;@Autowiredprivate OrderMapper orderMapper;@Transactional(transactionManager = "memberTransactionManager")public int addUser(String userName, Integer age) {int result = memberMapper.addUser(userName, age);orderMapper.inserOrder(userName);int j = 1 / age;return result;}}

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/userusername: rootpassword: rootborrowConnectionTimeout: 30loginTimeout: 30maintenanceInterval: 60maxIdleTime: 60maxLifetime: 20000maxPoolSize: 25minPoolSize: 3uniqueResourceName: orderDatasource###订单数据库order:url: jdbc:mysql://localhost:3306/orderusername: rootpassword: rootborrowConnectionTimeout: 30loginTimeout: 30maintenanceInterval: 60maxIdleTime: 60maxLifetime: 20000maxPoolSize: 25minPoolSize: 3uniqueResourceName: memberDatasource

5.1.2.3 读取配置文件信息
@ConfigurationProperties(prefix = "spring.datasource.member")@Datapublic class MemberConfig {private String url;private String userName;private String passWord;private int minPoolSize;private int maxPoolSize;private int maxLifetime;private int borrowConnectionTimeout;private int loginTimeout;private int maintenanceInterval;private int maxIdleTime;private String testQuery;private String uniqueResourceName;}

@ConfigurationProperties(prefix = "spring.datasource.order")@Datapublic class OrderConfig {private String url;private String userName;private String passWord;private int minPoolSize;private int maxPoolSize;private int maxLifetime;private int borrowConnectionTimeout;private int loginTimeout;private int maintenanceInterval;private int maxIdleTime;private String testQuery;private String uniqueResourceName;}

5.1.2.4 创建多数据源

@Configuration@MapperScan(basePackages = "com.tcf.member.mapper", sqlSessionTemplateRef = "memberSqlSessionTemplate")public class MemberDataSourceConfig {//@Configuration xml  MemberDataSourceConfig.xml/*** 创建我们的DataSource** @return*/@Bean("memberDataSource")public DataSource memberDataSource(MemberConfig memberConfig) throws SQLException {// 1.创建MysqlXADataSourceMysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();mysqlXaDataSource.setUrl(memberConfig.getUrl());mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);mysqlXaDataSource.setPassword(memberConfig.getPassWord());mysqlXaDataSource.setUser(memberConfig.getUserName());mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);// 2.将本地事务注册到创 Atomikos全局事务AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();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());return xaDataSource;}/*** 创建我们的SqlSessionFactory** @param dataSource* @return* @throws Exception*/@Bean(name = "memberSqlSessionFactory")public SqlSessionFactory memberSqlSessionFactory(@Qualifier("memberDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean.getObject();}
/*** 创建订单sqlSesion模版** @param sqlSessionFactory* @return* @throws Exception*/@Bean(name = "memberSqlSessionTemplate")public SqlSessionTemplate memberSqlSessionTemplate(@Qualifier("memberSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}
 
 
@Configuration@MapperScan(basePackages = "com.tcf.order.mapper", sqlSessionTemplateRef = "orderSqlSessionTemplate")public class OrderDataSourceConfig {//@Configuration xml  orderDataSourceConfig.xml/*** 创建我们的DataSource** @return*/@Bean("orderDataSource")public DataSource orderDataSource(OrderConfig orderConfig) throws SQLException {// 1.创建MysqlXADataSourceMysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();mysqlXaDataSource.setUrl(orderConfig.getUrl());mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);mysqlXaDataSource.setPassword(orderConfig.getPassWord());mysqlXaDataSource.setUser(orderConfig.getUserName());mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);// 2.将本地事务注册到创 Atomikos全局事务AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();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());return xaDataSource;}/*** 创建我们的SqlSessionFactory** @param dataSource* @return* @throws Exception*/@Bean(name = "orderSqlSessionFactory")public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);return sqlSessionFactoryBean.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")public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(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依赖;

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

原理:

实际上在开发写代码的时候 是不需要写getset方法,但是在编译class文件中,帮你自动生成好这样getset方法 放入到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 static Logger 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效果演示

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/741654.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第二证券|沪指窄幅震荡跌0.26%,半导体概念走强,保险板块跌幅居前

13日早盘&#xff0c;沪深两市窄幅震动&#xff0c;三大指数均小幅跌落。盘面上&#xff0c;人工智能方向团体反弹&#xff0c;半导体个股走势活跃。 到午间收盘&#xff0c;沪指跌0.26%&#xff0c;报3047.85点&#xff1b;深成指跌0.15%&#xff0c;报9615.92点&#xff1b;…

ruoyi-vue插件集成websocket

链接&#xff1a;插件集成 | RuoYi WebSocketServer.java&#xff1a;补充代码 /*** 此为广播消息* param message 消息内容*/public void sendAllMessage(String message) {LOGGER.info("【websocket.sendAllMessage】广播消息:"message);try {for(String sessionI…

工作中Promise用法总结

工作中Promise用法总结&#xff0c;后面会持续更新觉得有意义的。 1.构造Promise 一般情况下代码是这样的&#xff1a; async function fn() {return new Promise((resolve, reject) > {let list []resolve(list)} }await fn()最后的返回值&#xff0c;如果promise的状态…

谈谈杭州某小公司面试的经历

#面试#本人bg211本&#xff0c;一段实习&#xff0c;前几天面了杭州某小厂公司&#xff0c;直接给我干无语了&#xff01; 1、先介绍介绍你自己&#xff0c;我说了我的一个情况。 2、没获奖和竞赛经历吗&#xff1f;我说确实没有呢&#xff0c;面试官叹气了一下&#xff0c;只是…

300分钟吃透分布式缓存-27讲:Redis是如何进行主从复制的?

Redis 复制原理 为了避免单点故障&#xff0c;数据存储需要进行多副本构建。同时由于 Redis 的核心操作是单线程模型的&#xff0c;单个 Redis 实例能处理的请求 TPS 有限。因此 Redis 自面世起&#xff0c;基本就提供了复制功能&#xff0c;而且对复制策略不断进行优化。 通…

基于SWOT的智能手机企业财务战略研究1.62

摘 要 近些年&#xff0c;网络技术日新月异&#xff0c;智能手机深受消费者喜爱&#xff0c;人们通过网络&#xff0c;手机应用&#xff0c;可以极大地方便人们学习&#xff0c;工作等等。由于国家对电信行业的大力支持&#xff0c;中国消费者群体逐步成为最具潜力的手机购买者…

十六、接口隔离原则、反射、依赖注入

接口隔离原则、反射、特性、依赖注入 接口隔离原则 客户端不应该依赖它不需要的接口&#xff1b;一个类对另一个类的依赖应该建立在最小的接口上。 五种原则当中的i 上一章中的接口&#xff0c;即契约。 契约就是在说两件事&#xff0c;甲方说自己不会多要&#xff0c;乙方会在…

朴素贝叶斯算法基础——案例:对新闻进行分类

贝叶斯公式 朴素&#xff1a;假设特征与特征之间相互独立 朴素贝叶斯算法&#xff1a;朴素贝叶斯 应用场景&#xff1a;文本分类&#xff08;单词作为特征&#xff09; 拉普拉斯平滑系数 Ni&#xff1a;F1词在C类别所有文档中出现的次数 N&#xff1a;所属类别C下的文档所…

《C++游戏编程入门》第2章 真值、分支与游戏循环: Guess My Number

《C游戏编程入门》第2章 真值、分支与游戏循环: Guess My Number 2.1 关系运算符2.2 条件语句02.score_rater.cpp02.score_rater2.cpp02.score_rater3.cpp 2.5 switch语句02.menu_chooser.cpp 2.6 while循环02.play_again.cpp 2.7 do循环02.play_again2.cpp 2.8 break和continu…

AHU 数据库 实验三

《数据库》实验报告 【实验名称】 实验3 数据库的连接查询 【实验目的】 1. 熟悉基本的连接查询的概念和作用&#xff1b; 2. 了解数据库管理系统DBMS 实现连接查询的基本方法&#xff1b; 3. 掌握SQL语言连接查询语句的语法和功能&#…

.NET CORE Aws S3 使用

1.安装指定的包 Install-Package AWSSDK.S3 -Version 3.3.104.10 2.使用帮助类 using System; using System.Collections.Generic; using System.Text; using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using System.IO; using System.Threadi…

Spring存储基础知识

一、对象存储 1.创建bean对象 public class User {public void sayHi() {System.out.println("hi student");} } 2.bean存入Spring 在spring-config.xml&#xff0c;将 bean&#xff08;com.spring.demo.User&#xff09;存到 Spring 容器中&#xff0c;它的名称…

【数据结构学习笔记】选择排序

【数据结构学习笔记】选择排序 参考电子书&#xff1a;排序算法精讲 算法原理 首先在未排序序列中找到最小&#xff08;大&#xff09;元素&#xff0c;存放到排序序列的起始位置&#xff0c;然后&#xff0c;再从剩余未排序元素中继续寻找最小&#xff08;大&#xff09;元…

读取CSV数据并写入MySQL

import pandas as pd #import tushare as ts from sqlalchemy import create_engineimport baostock as bs #### 登陆系统 #### lg bs.login() # 显示登陆返回信息 print(login respond error_code:lg.error_code) print(login respond error_msg:lg.error_msg) #### 获取沪深…

STM32第十课:串口发送

一、usart串口 1.1 USART串口协议 串口通讯(Serial Communication) 是一种设备间非常常用的串行通讯方式&#xff0c;因为它简单便捷&#xff0c;因此大部分电子设备都支持该通讯方式&#xff0c;电子工程师在调试设备时也经常使用该通讯方式输出调试信息。在计算机科学里&…

主流数据库的区别

几个主流的数据库有&#xff1a; 1. MySQL&#xff1a;MySQL是一种关系型数据库管理系统&#xff0c;常用于Web应用程序开发和数据存储。 2. Oracle&#xff1a;Oracle是一种关系型数据库管理系统&#xff0c;由Oracle Corporation开发和销售。它广泛用于企业级应用程序中。 …

在使用qml的qmldir文件创建常用组件报错unknow component

解决方法&#xff1a;Qt Creator中的工具-->QML/JS-->重置代码模型 参考博文:QML自定义模块及qmldir的使用_同一资源文件目录下的qml模块使用-CSDN博客 不一样的地方是我给我的文件起了别名 以及我的qrc文件路径有前缀/qml 总体操作&#xff1a; 1.使用模块中的组件时…

线程与进程的区别、协程

1【线程与进程的区别、协程】 【1】 进程跟线程 进程&#xff08;Process&#xff09;和 线程&#xff08;Thread&#xff09;是操作系统的基本概念&#xff0c; 但是它们比较抽象&#xff0c; 不容易掌握。关于多进程和多线程&#xff0c;教科书上对经典的一句话“进程是资源分…

铭文:探索比特币世界的数字印记

铭文是什么&#xff1f; 铭文指的是在某种物品&#xff08;如石头、硬币、平板等&#xff09;上刻有文字。在比特币领域&#xff0c;铭文指的是刻在聪&#xff08;satoshi&#xff09;上的元数据。比特币的最小单位是聪&#xff0c;1比特币可分为1亿聪。每个聪都通过序数理论进…

解决WSL2的ubuntu20.04中安装docker出现无法连接的问题(Cannot connect to the Docker daemon)

wsl2的ubuntu20.04系统安装docker可以参考官网教程操作&#xff0c;我个人喜欢参考其中的离线安装方式&#xff1a;Install from a package。只需要按照官网一步步操作即可&#xff0c;跟普通的ubuntu20.04的安装是一样的步骤。 在安装完以后&#xff0c;发现一旦使用docker相…