SpringBoot第一天
概述
SpringBoot是一个用来快速构建Spring开发环境的一个具体的框架。
(1) 项目所依赖的jar包
Maven的继承和依赖传递
(2) 项目applicationContext.xml配置文件
自动装配
SpringBoot快速入门
步骤:
(1)创建一个maven项目(jar)
jar为什么能直接启动,通过浏览器访问?
SpringBoot直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包
(2)pom.xml添加依赖
com.itheima
demo_springboot
1.0-SNAPSHOT
(3)编写一个引导类
springBoot工程都有一个启动引导类,这是工程的入口
并在引导类上添加@SpringBootApplication注解
@SpringBootApplication
public class DemoSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringbootApplication.class, args);
}
}
(4)编写Controller,和之前一样
注意:spring的引导类只能访问到当前包下或者子包下的controller
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
(5)启动,通过浏览器进行访问
spring-boot-starter-web --> spring-boot-starter-parent --> spring-boot-depedencies
快速构建SpringBoot的开发环境
小结:
Spring Boot工程可以通过添加启动器依赖和创建启动引导类实现快速创建web工程。
spring-boot-starter-web默认的应用服务器端口是8080
注解替换XML配置方式
Spring(IOC/DI AOP)
<property name="" value="" | ref=""/>
·
SpringBoot不建议搭建使用XML的方式来配置,而是使用注解来替换XML.
@Configuration 声明一个类作为配置类,代替xml文件
@Bean :声明在方法上,将方法的返回值加入Bean容器,代替 标签
@Value :属性注入
@PropertySource(了解) :指定外部属性文件,
jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot_test
jdbc.username=root
jdbc.password=root
JdbcConfig:
/**
-
声明我们 JdbcConfig 是一个配置类
/
@Configuration
/* -
指定属性文件的路径是: classpath:jdbc.properties
*/
@PropertySource(“classpath:jdbc.properties”)
public class JdbcConfig {/**
- 通过 @Value 为属性注入值
*/
@Value("${jdbc.url}")
String url;
@Value("${jdbc.driverClassName}")
String driverClassName;@Value("${jdbc.username}")
String username;@Value("${jdbc.password}")
String password;/**
- 通过@Bean将 dataSource() 方法声明为一个注册Bean的方法,
- Spring会自动调用该方法,将方法的返回值 加入Spring容器中。
- @return
*/
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(driverClassName);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
- 通过 @Value 为属性注入值
测试:成功注入DataSource
SpringBoot中实现配置
在Spring Boot中,提供了一种新的属性注入方式,支持各种java基本数据类型及复杂类型的注入
@ConfigurationProperties(prefix=“jdbc”) : 可以注入多个
并且在类上添加Component注解
/**
- prefix=“jdbc” 读取属性文件中,前缀为jdbc的值。
- 在类上通过@ConfigurationProperties注解声明当前类为属性读取类
/
@Component
@ConfigurationProperties(prefix = “jdbc”)
public class JdbcProperties {
/*- 在类上定义各个属性,名称必须与属性文件中 jdbc. 后面部分一致
*/
private String url;
private String driverClassName;
private String username;
private String password;
// get … set …
}
- 在类上定义各个属性,名称必须与属性文件中 jdbc. 后面部分一致
需要注意的是,这里我们并没有指定属性文件的地址,所以我们需要把jdbc.properties名称改为 application.properties,这是Spring Boot默认读取的属性文件名
从配置文件中获取以xxx开头的所有属性来注入到JdbcProperties 类的属性名中。
properties
jdbc.driver_class_name=com.mysql.jdbc.Driver
/**
-
声明我们 JdbcConfig 是一个配置类
/
@Configuration
/* -
通过 @EnableConfigurationProperties(JdbcProperties.class)
-
来声明要使用 JdbcProperties 这个类的 对象
*/
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {// 声明有@Bean的方法参数注入
@Bean
public DataSource dataSource(JdbcProperties jdbc){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbc.getUrl());
dataSource.setDriverClassName(jdbc.getDriverClassName());
dataSource.setUsername(jdbc.getUsername());
dataSource.setPassword(jdbc.getPassword());
return dataSource;
}
}
我们直接把 @ConfigurationProperties(prefix = “jdbc”) 声明在需要使用的 @Bean 的方法上,然后Spring Boot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属 性的set方法!
/**
- 如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类
- 而是直接在需要的地方声明即可
- @return 返回值为注入的DataSource
*/
@ConfigurationProperties(prefix = “jdbc”)
@Bean
public DataSource dataSource(){
return new DruidDataSource();
}
使用ConfigurationProperties注入的优势
@Value:一次只能注入一个属性
配置文件除了可以使用application.properties类型,还可以使用后缀名为:.yml或者.yaml的类型,也就是: application.yml或者application.yaml
applicaiton.yml
application.yaml
application.properties
!!!如果两个配置文件都有,会把两个文件的配置合并,如果有重复属性,以properties中的为准。
基本格式:
yml中的使用格式
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: root
普通属性的注入
username1: zhangsan
对象的注入
user:
username: lisi
age: 20
gender: 1
address: beijing
order:
number: 18
totol: 330
name: wangwu
对象方式2
user2: {username: zhaoxin, age: 20,gender: 1}
集合
city:
- beijing
- zhejiang
- nanjing
集合2
city2: [dongbei, xibei, huabei]
对象中包含集合
student:
name: zhangsan
age: 18
order:
- 20180808
- 20190909
- 20202020
集合中包含对象
person:
- xian: yixian
name: lisi
age: 70 - shanghai: yixian
name: wangwu
age: 80
package live.longmarch.demo_springboot2.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
/**
-
@PackageName: live.longmarch.controller
-
@ClassName: HelloController
-
@Author: gaoning
-
@Date: 2020/1/9 20:46
-
@Blame: liunian
-
@Description:
*/
@RestController
@RequestMapping("/hello")
public class HelloController {@Autowired
private DataSource dataSource;@Value("${username1}")
String username1;@Value("${user.address}")
String address;@Value("${order.name}")
String name;@Value("${user2.username}")
String name2;@Value("${city[2]}")
String city;@Value("${city2[2]}")
String city2;@Value("${student.order[2]}")
Integer orderDate;@Value("${person[1].age}")
Integer age;
@RequestMapping("/springboot")
public String sayHello(){
System.out.println(username1);
System.out.println(address);
System.out.println(name);
System.out.println(name2);
System.out.println(city);
System.out.println(city2);
System.out.println(orderDate);
System.out.println(age);
System.out.println("dataSource = " + dataSource);
return “hello!”;
}
}
SpringBoot使用lombok
解决的问题: POJO
public class Xxx{
private Long id;
private String username;
…
//setter…getter…
//toString
//构造函数
}
作用:简化POJO/domain/模型类的编写。
使用步骤:
(1)安装插件
(2)pom.xml添加依赖
org.projectlombok
lombok
(3)
@Data
@AllArgsConstructor //全参构造函数 这两个注解同时加
@NoArgsConstructor //无参构造函数
@Slf4j //相对于声明了一个 log对象,可以直接通过log对象的方法来实现日志记录
public class User {
//public static final Logger log = LoggerFactory.getLogger(User.class);
private Integer id;
private String username;
public static void main(String[] args) {
log.debug("这是debug消息");
log.info("这是info消息");
log.warn("这是warn消息");
log.error("这是error消息");
}
}
SpringBoot如何调整端口,静态资源存放位置
端口:
server:
port: 80
springboot默认会加载三类配置文件,后面加载的内容会覆盖前面配置文件的相同属性名的属性值
静态资源:
springboot的静态资源,可以放置在resources的static目录下
SpringBoot整合SpringMVC的拦截器实现步骤(了解)
(1)编写一个拦截器类
public class MyInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//执行handler之前,放行return true,拦截return false
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//执行handler之后
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//视图解析器解析完以后
}
}
(2)配置文件配置拦截器类
springmvc.xml
mvc:interceptors
mvc:interceptor
<mvc:mapping path="/**"/>
</mvc:interceptor>
</mvc:interceptors>
SpringBoot注解配置
@Configuration
public class MvcConfig implements WebMvcConfigurer{
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
}
}
SpringBoot整合Mybatis操作数据库
Mysql数据库的驱动导入
SpringBoot整合数据库连接池
数据库连接的四要素
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///test
username: root
password: 123456
SpringBoot整合事务管理
pom.xml spring-boot-starter-jdbc
@Transactional
接口、类、方法
接口:实现该接口的所有类的所有方法上
类:当前类的所有方法
方法:具体方法有事务
SpringBoot整合Mybatis
(1)pom.xml
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
非官方提供,父项目中就不会管理对应的version,自己加
(2) application.yml配置信息
mybatis:
type-aliases-package: com.itheima.domain #包扫描 resultType/resultMap /parameterType
mapper-locations: mappers/*.xml #找到映射文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #将操作对应的sql语句显示在控制台,调试错误
(3)编写Mapper接口和Mapper映射文件
四个规范:
(1)Mapper接口的类全名要和Mapper映射文件的namespace保持一致
(2)Mapper接口的方法名要和Mapper映射文件的statementId保持一致
(3)Mapper接口的方法参数要和Mapper映射文件的parameterType保持一致
(4)Mapper接口的方法返回值要和Mapper映射文件的resultType/resultMap保持一致
(4)引导类添加包扫描
import org.mybatis.spring.annotation.MapperScan;
@MapperScan(“com.itheima.dao”)
通用Mapper简化Mybatis的开发原理
SpringBoot整合通用Mapper
(1)pom.xml添加起步依赖
tk.mybatis
mapper-spring-boot-starter
2.1.5
(2)application.yml添加配置
无
(3)编写模型类建立模型类和数据库表的关系
@Table(name=“tb_user”)
@Data
public class User {
@Id
@KeySql(useGeneratedKeys = true)
private Integer id;
@Column(name="user_name")
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private String note;
private Date created;
private Date updated;
}
(4)编写Mapper接口类
public interface UserMapper extends Mapper{
}
(5)引导类上添加包扫描
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan(“com.itheima.dao”)
(6)实现增删改查
SpringBoot整合Junit来完成测试
(1)pom.xml
org.springframework.boot
spring-boot-starter-test
(2)
package com.itheima.test;
import com.itheima.springboot_1.Springboot1Application;
import com.itheima.springboot_1.domain.User;
import com.itheima.springboot_1.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Springboot1Application.class)
public class MyTest {
@Autowired
private UserMapper userMapper;
@Test
public void testAdd(){
User user = new User(null,"JERRY",new Date(),20000.0);
userMapper.insert(user);
}
@Test
public void testDel(){
userMapper.deleteByPrimaryKey(2);
}
@Test
public void testUpdate(){
User user = userMapper.selectByPrimaryKey(1);
user.setName("赵敏");
user.setBirthday(new Date());
userMapper.updateByPrimaryKey(user);
}
}
SpringBoot整合Redis
(1) pom.xml添加起步依赖
org.springframework.boot
spring-boot-starter-data-redis
(2)application.yml添加配置
spring:
redis:
host: 127.0.0.1
port: 6379
(3) 使用RedisTemplate
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Springboot1Application.class)
public class MyTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testAddData(){
//Value,List,Hash,Set,ZSet(SortedSet)
redisTemplate.boundValueOps("itheima").set("itcast");
redisTemplate.opsForValue().set("itheima","itcast");
}
@Test
public void testGetData(){
Object rst = redisTemplate.boundValueOps("itheima").get();
redisTemplate.opsForValue().get("itheima");
System.out.println(rst);
}
}
思考:
RedisTemplate从哪里来?
@Bean
但是@Autowired注入了RedisTemplate,
为什么包结构不一样,无法获取资源?
Springboot默认会扫描引导类所在包及其子包中所有类上的注解
SpringBoot部署
tomcat/webapps/xxx.war
springboot---->xxx.jar
pom.xml
org.springframework.boot
spring-boot-maven-plugin
自动配置原理
SpringBoot为我们提供了默认配置,而默认配置生效的步骤:
@EnableAutoConfiguration注解会去寻找 META-INF/spring.factories 文件,读取其中以 EnableAutoConfiguration 为key的所有类的名称,这些类就是提前写好的自动配置类 这些类都声明了 @Configuration 注解,并且通过 @Bean 注解提前配置了我们所需要的一切实例 但是,这些配置不一定生效,因为有 @ConditionalOn 注解,满足一定条件才会生效。比如条件之一:是一些 相关的类要存在 类要存在,我们只需要引入了相关依赖(启动器),依赖有了条件成立,自动配置生效。 如果我们自己配置了相关Bean,那么会覆盖默认的自动配置的Bean 我们还可以通过配置application.yml文件,来覆盖自动配置中的属性 1)启动器
所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的 stater(启动器),就会自动管理依赖及版本了。 因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器 2)全局配置
另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义 application.properties 文件来 进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。
因此,玩SpringBoot的第二件事情,就是通过 application.properties 来覆盖默认属性值,形成自定义配置。我 们需要知道SpringBoot的默认属性key,非常多,可以再idea中自动提示、
学习总结 :
在application.properties / application.yml / appcation.yaml 中 配置属性的值
在config中
- 声明我们 JdbcConfig 是一个配置类
@Configuration - 通过 @Value 为属性注入值
@Value(" j d b c . u r l " ) S t r i n g u r l ; @ V a l u e ( " {jdbc.url}") String url; @Value(" jdbc.url")Stringurl;@Value("{jdbc.driverClassName}")
String driverClassName;
@Value(" j d b c . u s e r n a m e " ) S t r i n g u s e r n a m e ; @ V a l u e ( " {jdbc.username}") String username; @Value(" jdbc.username")Stringusername;@Value("{jdbc.password}")
String password;
在@SpringBootApplication 注解标识的类中配置启动器
在controller中书写代码
问题:
Spring开发中遇到的问题?
SpringBoot用来快速构建Spring的开发环境,针对上述问题,具体的解决方案是?
SpringBoot开发环境构建的步骤?
SpringBoot中对应注解的作用?
@Configuration @Bean @Value @ConfigurationProperties
SpringBoot配置文件内容
application.yml中语法结构?
application.yml和application.properties加载顺序?
SpringBoot中如何使用lombok?
SpringBoot如何调整端口和使用静态资源?
SpringBoot整合Mybatis / Redis /JunitTest
拓展:SpringBoot如何整合Freemarker?
SpringBoot如何部署?