SpringBoot入门
1.SpringBoot简介
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
-
简化Spring应用开发一个框架
-
完成整个Spring技术栈的一个大整合
-
J2EE开发一站式解决方案
-
可以看做是spring的一个封装,帮我们完成自动化的配置,减少配置的过程,把精力放在纯业务开发上
3. SpringBoot入门程序
手动创建springBoot web项目的方式
-
创建一个传统的maven项目(jar方式)
-
在pom文件中的添加SpringBoot的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hwua</groupId>
<artifactId>SpringBoot_Demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
<!--只针对stsIDE maven兼容性的问题, IteliJJ IDEA 不需要-->
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> -
创建一个web层的控制器类
package com.hwua.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
-
创建SpringBoot的启动类
package com.hwua;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
总结: 以下步骤我们都没有做,它怎么实现运行的
1. 没有手动导入Spring,SpringMVC等jar包
-
没有编写xml配置文件
-
没有配置tomcat服务器
4.Hello World 程序探究
1.查看pom文件中的父项目
父项目
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
父项目的父项目
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
他来真正管理SpringBoot应用里面的所有jar包的依赖版本,称为"springBoot版本控制中心"
2.启动器
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
spring-boot-starter-web:场景启动器,帮我们导入web模块正常运行所依赖的jar组件
好处:不用一个个jar包手动依赖,而是根据我们开发的应用场景选择场景启动器即可,它会自动帮我们完成场景所运用到的所有jar包的依赖.
3.主程序类,主入口类分析
@SpringBootApplication: SpringBoot应用标注这个注解,代表这个类就是一个主配置类.说明此类是SpringBoot应用的启动类
@SpringBootConfiguration 就是一个Spring中的 @Configuration注解,就是一个配置类
@EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
@AutoConfigurationPackage:自动配置包扫描
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
}
@Import(AutoConfigurationPackages.Registrar.class) 导入Registrar配置类,在主配置类中确定扫描的包是主程序类所在的包或它的子包.
@Import(AutoConfigurationImportSelector.class) //导入自动配置类,将所需要导入的组件以全类名的方式返回, 返回的这些组件(自动配置类)就会被添加到容器中
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\ org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\ org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
当SpringBoot启动的时候,会帮我们创建很多的自动配置类,就是给同期导入这个场景需要的所有组件,并配置好这些组件. SpringBoot在启动时,获取EnableAutoConfiguration 注解指定的值
自动配置类都放在这个jar包中: spring-boot-autoconfigure-2.1.6.RELEASE.jar
5.利用IDE 快速创建一个spring-boot程序
6.YMAL (YAML Ain't Markup Language)
它是以数据为中心,比json和xml更适合做配置文件
SpringBoot提供两种配置文件
1. properties 配置文件 2. yml或yaml配置文件
作用:
-
配置数据
-
修改自动配置类默认配置参数
yml 格式:
server: port: 9999
键与键之间 冒号回车 空格,键和值之间 冒号 空格,键值是区分大小的
6.1 值的写法
字面量:普通的值(数字,字符串,布尔类型值)
key:value: 字面量直接写值
字符串默认不加单引号或双引号.
1. 双引号: 值里面有特殊符号,会进行转义,比如"chenhao\nzhangsan" ,输出chenhao换行 zhangsan
-
单引号: 值里面有特殊符号,不会进行转义,比如'chenhao\nzhangsan' ,输出chenhao\n zhangsan
6.2.properties配置
teacher.username=chenhao teacher.age=39 teacher.email=xxxx@qq.com teacher.pet.brand=\u4E2D\u534E\u7530\u56ED\u72AC
6.3.yml配置
teacher:
username: 张三
age: 10
email: 2w2233@qq.com
pet:
brand: 拉布拉多
6.4@ConfigurationProperties 和@Value 属性值注入的对比
| 功能 | @ConfigurationProperties | @Value |
|---|---|---|
| 注入功能 | 批量注入 | 一个个注入 |
| 松散语法 | 支持 | 不支持 |
| spel | 支持 | 支持 |
| JSR303 | 支持 | 不支持 |
| 是否支持复杂类型的注入 | 支持 | 不支持 |
6.5. SpringBoot 默认只会导入application.properties和application.yml 两个配置文件,要导入其它的属性配置文件(properties),可以使用@PropertySource来导入
@PropertySource({"classpath:config.properties",""})
public class Teacher {
private String userName;
private Integer age;
private String email;
6.6.SpringBoot默认会加载很多自动配置类,那要是我们想用自己的配置文件,是否可以做到.(@ImportResource注解来加载自定义的配置文件)
@ImportResource("classpath:beans.xml")
public class Application {
6.7.Springboot虽然可以使用@ImportResource来加载xml配置文件,但springBoot推荐使用配置类来代替配置文件,SpringBoot使用全注解的方式来进行配置
package com.hwua.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.hwua.entity.Teacher;
//此注解代表配置类,当扫描到会在容器中创建对象
@Configuration
public class TeacherConfig {
//当扫描到含有@Bean方法时,此方法会自动执行,并把返回值放到spring容器中
@Bean
public Teacher teac() {
return new Teacher();
}
}
6.8. 使用properties配置文件来实现多环境切换
可以编写多个properties文件,语法规则application-环境名.properties
application-dev.properties
server.port=8889
application-test.properties
server.port=9999
要切换的话在主配置文件中指定applicationContext.properties
server.port=80
spring.profiles.active=test //指定要切换的环境
6.9 使用yml配置文件来实现多环境切换
server:
port: 80
spring:
profiles:
active: dev
---
server:
port: 8889
spring:
profiles: dev
---
server:
port: 9999
spring:
profiles: test
7.0 多环境的动态切换(做补救措施,在不改变原配置文件的情况下来完成切换)
-
使用sts运行时配置,指定运行时参数
--spring.profiles.active=dev
-
在命令行指定运行参数来切换环境
java -jar Spring_Boot_1_2019.7.1-0.0.1-SNAPSHOT.jar --spring.profiles.active=test
-
设置VM参数来切换运行环境
-Dspring.profiles.active=dev
7. 配置文件存放的路径:
7.1. 项目内路径
file:./config/ file:./ classpath:./config/ classpath:./
提示:优先级从上往下
7.2. 项目外路径(做补救措施)
--spring-config-location=d:/application.yml
8.SpringBoot整合日志
8.1 常用的日志
jcl,jul,log4j,log4j2,slf4j,logback,jboss-logging ..... Spring 默认日志处理使用jcl,而pringBoot使用的是slf4j-->logback
8.2. 整合步骤,主要就是配置
package com.hwua;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
// 创建一个日志记录对象
Logger logger = LoggerFactory.getLogger(ApplicationTests.class);
@Test
public void contextLoads() {
logger.trace("trace.....");
logger.debug("debug.....");
logger.info("info.....");
logger.warn("warn.....");
logger.error("error.....");
}
}
在properties/yml配置文件中文件中进行配置
logging.level.com.hwua=trace #在哪个应用中开启日志记录,使用的日志开关等级
logging.file=chenhao.log #在当前当目中创建日志文件
#logging.path=d:/chenhao # 你指定目录文件中创建日志文件
logging.pattern.console="%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %m%n" #在控制台显示日志的格式
logging.pattern.file="%d{yyyy-MM-dd HH:mm:ss} %5p **** %m%n" #在日志文件中记录日志的格式
9.SpringBoot处理web静态资源
static : 存放静态资源,比如:图片,css文件,js文件等
templates: 存放的是模板页面,比如freemarker,thymeleaf
9.1 访问静态资源的方式有两种
-
使用webjars来访问静态资源--webjars就是把静态资源打包成一个jar,再把jar包依赖到项目中即可,一般推荐使用第三方的静态资源,比如jquery,bootstrap等等..
http://localhost:9999/webjars/jquery/3.4.1/jquery.js
-
springBoot默认存放的静态资源路径
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"
-
设置欢迎页面
只要创建一个名字叫index.html文件,放到任意一个默认存放静态资源的目录下即可
-
设置默认图标
创建一个名字叫favicon.ico的图标文件,放到任意一个默认的静态资源目录下即可
9.2 SpringBoot访问动态资源
-
动态资源:
jsp,freemaker,thymeleaf,springBoot默认不支持jsp
-
什么叫模板引擎
就网页结构和模型数据分离,两者交给模板引擎,做种完成页面的渲染
-
Springboot对Thymeleaf的自动配置 ThymeleafAutoConfiguration 自动配置类
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
-
创建一个thymeleaf模板页面
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>首页</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/javascript" th:src="@{/js/jquery.js}"></script> <script> $(function(){ alert("HELLO"); }) </script> </head> <body> <ul th:each="teacher:${list}"> <li th:text=${teacher.userName}></li> <li th:text=${teacher.age}></li> <li th:text=${teacher.email}></li> <li th:text=${teacher.pet.brand}></li> </ul> </body> </html>-
SpringBoot整合C3P0
-
导入jar包
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> -
创建C3P0数据源对象放到容器中,手动创建配置类对象(创建ComBopooledDataSource对象)
c3p0.datasource.user=root c3p0.datasource.password=123456 c3p0.datasource.jdbcUrl=jdbc:mysql://localhost:8888/msgdb c3p0.datasource.driverClass=com.mysql.cj.jdbc.Driver
@Component public class C3P0Config { @Bean @ConfigurationProperties(prefix="c3p0.datasource")//把属性注入到创建的数据源当中 public DataSource dataSource() { return new ComboPooledDataSource(); } } -
SpringBoot整合MyBatis
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>
-
全注解的方式(不做任何修改,直接编写mapper接口即可)
package com.hwua.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import com.hwua.entity.User; @Mapper //包扫描的时候一旦扫到此注解修饰的接口,就会帮我们创建一个代理类对象 public interface UserMapper { @Insert("insert into users values (null,#{name},#{pwd},#{email})") public int saveUser(User user) throws Exception; @Select("select id,name,pwd,email from users where id=#{id}") public User findUserById(Integer id) throws Exception; } -
xml结合注解
-
创建一个mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration> -
配置MapperSQL映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hwua.mapper.UserMapper"> <select id="findUserById" resultType="user"> select id,name,pwd,email from users where id=#{id} </select> <insert id="saveUser" parameterType="user"> insert into users values (null,#{name},#{pwd},#{email}) </insert> </mapper> -
在主配置文件中进行mybatis相关配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.type-aliases-package=com.hwua.entity mybatis.mapper-locations=classpath:com/hwua/mapper/*.xml
回家作业:
使用SpringBoot整合thymeleaf,c3p0,mybatis,springmvc 来完成用户表增删改查操作
-
-
-
-
-
posted on 2019-07-28 10:15 Pinghu_gary 阅读(126) 评论(0) 收藏 举报
浙公网安备 33010602011771号