SpringBoot2核心技术-基础入门


SpringBoot2核心技术-基础入门雷神笔记
springboot官方文档

一 SpringBoot2入门

1、系统要求

● Java 8 & 兼容java14 .
● Maven 3.3+
● idea 2019.1.2

1.1、maven设置

修改 D:\apache-maven-3.5.2\conf\settings.xml 参数

<mirrors>
    <mirror>
      <id>nexus-aliyun</id>
      <mirrorOf>central</mirrorOf>
      <name>Nexus aliyun</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>
</mirrors>
 
<profiles>
       <profile>
            <id>jdk-1.8</id>
            <activation>
              <activeByDefault>true</activeByDefault>
              <jdk>1.8</jdk>
            </activation>
            <properties>
              <maven.compiler.source>1.8</maven.compiler.source>
              <maven.compiler.target>1.8</maven.compiler.target>
              <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
            </properties>
       </profile>
</profiles>

2、HelloWorld

需求:浏览器发送/hello请求,服务器响应 Hello,Spring Boot 2

2.1、创建maven工程

create project -> maven -> 不勾create ->

2.2、引入依赖

在pom.xml中添加

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
</parent>

<!--web场景启动器-->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

</dependencies>

2.3、创建主程序

在src/main/java下新建class: com.yu.boot.MainApplication

/**
 * 主程序类
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

2.4、编写业务

在src/main/java下新建class: controller.HelloController

@RestController
public class HelloController {


    @RequestMapping("/hello")
    public String handle01(){
        return "Hello, Spring Boot 2!";
    }

}

2.5、测试

直接运行main方法

2.6、简化配置

配置列表
在resources下新建:
application.properties

server.port=8888

2.7、简化部署

在pom.xml中添加

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
把项目打成jar包,直接在目标服务器执行即可。

存放在

执行jar包

java -jar boot-01-helloworld-1.0-SNAPSHOT.jar

注意点:
● 取消掉cmd的快速编辑模式

二 了解自动配置原理

1、SpringBoot特点

1.1、依赖管理

● 父项目做依赖管理

依赖管理    
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
</parent>

他的父项目
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>

几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制

● 开发导入starter场景启动器

1、见到很多 spring-boot-starter-* : *就某种场景
2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
3、SpringBoot所有支持的场景

https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

4、见到的  *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
5、所有场景启动器最底层的依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.3.4.RELEASE</version>
  <scope>compile</scope>
</dependency>

● 无需关注版本号,自动版本仲裁

1、引入依赖默认都可以不写版本
如:
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
2、引入非版本仲裁的jar,要写版本号。

● 可以修改默认版本号

1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
2、在当前项目里面重写配置
  在pom.xml中添加

    <properties>
        <mysql.version>5.1.43</mysql.version>
    </properties>

1.2、自动配置

● 自动配好Tomcat
  ○ 引入Tomcat依赖。
  ○ 配置Tomcat

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.3.4.RELEASE</version>
      <scope>compile</scope>
    </dependency>
● 自动配好SpringMVC
  ○ 引入SpringMVC全套组件
  ○ 自动配好SpringMVC常用组件(功能)
● 自动配好Web常见功能,如:字符编码问题
  ○ SpringBoot帮我们配置好了所有web开发的常见场景
● 默认的包结构
  ○ 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
        比如创建一个WorldController,放在yu下就不会被默认扫描
  ○ 无需以前的包扫描配置
  ○ 想要改变扫描路径,在主程序类中修改为 @SpringBootApplication(scanBasePackages="com.yu")
       或者@ComponentScan 指定扫描路径
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.yu.boot")
● 各种配置拥有默认值
  ○ 默认配置最终都是映射到某个类上,如:MultipartProperties
  ○ 配置文件的值最终会绑定某个类上,这个类会在容器中创建对象
● 按需加载所有自动配置项
  ○ 非常多的starter
  ○ 引入了哪些场景这个场景的自动配置才会开启
  ○ SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面
  ○

2、容器功能

添加yu.boot.bean.Pet和User
Pet

package com.yu.boot.bean;

/**
 * 宠物
 */
public class Pet {
    private String name;

    public Pet() {
    }

    public Pet(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                '}';
    }
}


User

package com.yu.boot.bean;

public class User {
    private String name;
    private Integer age;

    private Pet pet;
    public User() {
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Pet getPet() {
        return pet;
    }

    public void setPet(Pet pet) {
        this.pet = pet;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", pet=" + pet +
                '}';
    }
}


在resources下new一个 xml configuration file ->spring config -> beans.xml
beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user01" class="com.yu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="13"></property>
    </bean>

    <bean id="cat" class="com.yu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

上面是用Spring的xml配置方式,springboot中不需要

2.1 组件添加

1、@Configuration

组件单实例

● 基本使用
● Full模式与Lite模式
  ○ 示例
  ○ 最佳实战
  ■ 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
  ■ 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

在boot下新建一个class: config.MyConfig

#############################Configuration使用示例######################################################
/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、配置类本身也是组件
 * 3、proxyBeanMethods:代理bean的方法
 *      Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 *      Lite(proxyBeanMethods = false)【轻量级模式,每个@Bean方法被调用多少次返回的组件都是新创建的】
 *      组件依赖必须使用Full模式默认。其他默认是否Lite模式
 *
 *
 *
 */
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件 默认proxyBeanMethods是true
public class MyConfig {

    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;       
    }

    @Bean("tom")          
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

MainApplication.java


################################@Configuration测试代码如下########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.yu.boot")
public class MainApplication {

    public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        //3、从容器中获取组件

        Pet tom01 = run.getBean("tom", Pet.class);

        Pet tom02 = run.getBean("tom", Pet.class);

        System.out.println("组件:"+(tom01 == tom02));


        //com.yu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$9b515a23@535b8c24
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);

        //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
        //保持组件单实例
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println(user == user1);


        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);

        System.out.println("用户的宠物是不是容器的:"+(user01.getPet() == tom));

        //5 获取组件
        String[] beanNamesForType = run.getBeanNamesForType(User.class);
        System.out.println("=====================");
        for (String s : beanNamesForType) {
            System.out.println(s);
        }

        DBHelper bean1 = run.getBean(DBHelper.class);
        System.out.println(bean1);

    }
}

2、@Component等

@Component:泛指各种组件(把普通pojo实例化到spring容器中,相当于配置文件中的
@Controller:控制器(注入服务)
@Service:业务逻辑组件(注入dao)
@Repository:数据库层组件(实现dao访问)

3、@ComponentScan:指定包扫描规则,

为理解底层源码,接下来看一些常见的底层注解

4、@Import:导入组件 (导入配置类或者一些需要前置加载的类)
 /* 4、@Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 *
 */

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
}

@Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8

5、@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入
ctrl+N 搜素 @Conditional 然后ctrl+H打开继承树

@ConditionalOnBean :容器中有指定组件时才
@ConditionalOnMissingBean :容器中没有指定组件时才
@ConditionalOnClass :容器中有某个类时才
@ConditionalOnResource :项目的类路径中存在某一资源时才
@ConditionalOnJava :是某一指定版本号时才
@ConditionalOnWebApplication :当是一个web应用时才
@ConditionalOnNotWebApplication :当不是一个web应用时才
@ConditionalOnSingleCandidate :容器中指定组件只有一个实例,或只有一个主实例

MyConfig.java

=====================测试条件装配==========================
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {


    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */
    //@ConditionalOnBean(name = "tom")
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom22")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

MainApplication.java

public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2、查看容器里面的组件
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        boolean tom = run.containsBean("tom");
        System.out.println("容器中Tom组件:"+tom);

        boolean user01 = run.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);

        boolean tom22 = run.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);


    }

2.2、原生配置文件引入

1、@ImportResource 导入资源

beans.xml

======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

MyConfig.java

@ImportResource("classpath:beans.xml")
public class MyConfig {}

MainApplication.java

        //======================测试=================
        boolean haha = run.containsBean("haha");
        boolean hehe = run.containsBean("hehe");
        System.out.println("haha:"+haha);//true
        System.out.println("hehe:"+hehe);//true

2.3、配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;
在之前我们需要

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

现在我们可以通过注解来实现
application.properties

mycar.brand = BYD
mycar.price = 10000000
1、@Component + @ConfigurationProperties

在beans下新建一个 Car

/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能 所以需要@Component
 */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

测试
HelloController.java

    @Autowired
    Car car;
    
    @RequestMapping("/car")
    public Car car(){
        return car;
    }
2、@EnableConfigurationProperties + @ConfigurationProperties

MyConfig.java

@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
...
}

这样就可以不用加@Component
Car.java

//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {


测试
HelloController.java

    @Autowired
    Car car;
    
    @RequestMapping("/car")
    public Car car(){
        return car;
    }

3、自动配置原理入门

3.4 实践

SpringBoot应用如何编写?

● 引入场景依赖
    ○ https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

● 查看自动配置了哪些(选做)
    ○ 自己分析,引入场景对应的自动配置一般都生效了
    ○ 配置文件application.properties中 debug=true 开启自动配置报告。      Negative(不生效)\Positive(生效)
● 是否需要修改
    ○ 参照文档修改配置项
        ■ https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

        ■ 自己分析。xxxxProperties绑定了配置文件的哪些。                              
例如:


将文件导入到resources下
那么在application.properties添加如下代码即可

spring.banner.image.location=classpath:222.jpg
    ○ 自定义加入或者替换组件
        ■ @Bean、@Component。。。
    ○ 自定义器  XXXXXCustomizer;
......

4、开发小技巧

4.1、Lombok

pom.xml

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

idea中搜索安装 lombok 插件(settings的plugins)

简化JavaBean开发

在User中添加 @Data 和 @ToString
@AllArgsConstructor 全参构造器
@NoArgsConstructor 无参构造器
@EqualsAndHashCode 重写hashcode和equals方法

//===============================简化JavaBean开发===================================
@NoArgsConstructor
//@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class User {

    private String name;
    private Integer age;

    private Pet pet;

    public User(String name,Integer age){
        this.name = name;
        this.age = age;
    }


}
简化日志开发

在HelloController.java中添加
@Slf4j
就可以添加 log.info

  //================================简化日志开发===================================
@Slf4j
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
        
        log.info("请求进来了....");
        
        return "Hello, Spring Boot 2!"+"你好:"+name;
    }
}

4.2、dev-tools 热更新(重启)

在pom.xml中添加

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

项目或者页面修改以后:Ctrl+F9 就可以实现热更新

4.3、Spring Initailizr(项目初始化向导)

0、选择我们需要的开发场景

new project -> Spring Initializr -> default ->


如果没有对应版本,可以进去修改

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

删去暂时没用的

和.mvn

1、自动依赖引入

2、自动创建项目结构

3、自动编写好主配置类

posted @ 2021-07-06 08:36  星空与沧海  阅读(116)  评论(0编辑  收藏  举报