2021-08-24 spring boot2 学习笔记

本文详细介绍了SpringBoot的入门步骤,包括Maven配置、创建工程、引入父项目和starter,以及主程序和Controller的编写。此外,还探讨了SpringBoot的自动配置原理、依赖管理和启动器功能。最后讲解了配置绑定、条件装配和组件注册等核心概念。
摘要由CSDN通过智能技术生成

spring boot 入门

maven的设置

找到maven安装目录里的/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>

<!-- 在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>

创建maven 工程

  • 参考官方文档引入一下配置
	<!-- 引入父项目 -->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
    </parent>
	
	<!-- 引入starter,引入后就会自动下载一些jar包 -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

	<!-- 引入build方式,build完之后的jar包可以直接在命令行运行启动服务 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 创建主程序类
package com.study.springboot2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * 主程序类
 * @SpringBootApplication:表示这是一个springboot应用
 */
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class);
    }
}

  • 创建controller类
package com.study.springboot2.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @RestController = @ResponseBody + @Controller
 * @ResponseBody注解的作用是可以将该类下所有方法的返回值直接写在页面上
 */
@RestController
public class HelloWordController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello world";
    }
}

spring boot里所有具体的配置都是在application.properties里(需要新建),具体参考
官方文档.

了解自动配置原理

依赖管理

  • 父项目进行依赖管理
    这是该工程中的父项目
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
    </parent>

这个是父项目里的父项目,而spring-boot-dependencies里定义了几乎所有常用依赖的版本,且版本都是根据spring boot的版本进行自动版本仲裁

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.5.4</version>
  </parent>

如果需要自定义依赖的版本,在propertis里指定

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

<properties>
	<mysql.version>8.0.26</mysql.version>
</properties>
  • starter 场景启动器
  1. 只要引入starter,这个场景的所有常规依赖都会自动引入
  2. starter的支持场景.
  3. 所有场景启动器最底层的依赖
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.5.4</version>
      <scope>compile</scope>
    </dependency>

自动配置

在引入spring-boot-starter-web场景启动器之后

  • 自动配好tomcat
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.5.4</version>
      <scope>compile</scope>
    </dependency>
  • 自动配好SpringMVC
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.9</version>
      <scope>compile</scope>
    </dependency>
  • 自动配好web常见功能,如:字符编码问题
  • 默认的包结构
    默认扫描主程序所在的包及其下面所有的子包
    @SpringBootApplication = @SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan

如果想要改遍扫描路径,可以用@ComponentScan指定或者@SpringBootApplication(scanBasePackages = )指定

  • 各种配置拥有默认值,配置文件的值最终都会映射到对应的类,这个类会在容器中创建对象
  • 按需加载所有自动配置项
    有非常多的starter,引入哪个场景启动器,这个场景的自动配置才会开启
    自动配置的功能是通过spring-boot-autoconfigure实现的

容器功能

创建配置类用来代替配置文件

package com.study.springboot2.config;

import com.study.springboot2.bean.Pet;
import com.study.springboot2.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Full(proxyBeanMethods = true)    
 * Lite(proxyBeanMethods = false)  轻量级
 */
@Configuration(proxyBeanMethods = false)
//标识这是一个配置类
public class MyConfig {
    @Bean
    //给容器添加组件,默认方法名作为bean id
    public User user1(){
        return new User("111","man");
    }
    @Bean("tomtom")
    //指定beanid为tomtom
    public Pet pet(){
        return new Pet("tom");
    }
}

proxyBeanMethods默认是true,true时为单例,在每次调用这个bean时springboot都会扫描看容器里是不是有这个组件,比较慢
如果为false,此时不会扫描,调用一次就创建一个新的对象

package com.study.springboot2;

import com.study.springboot2.bean.Pet;
import com.study.springboot2.bean.User;
import com.study.springboot2.config.MyConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * 主程序类
 * @SpringBootApplication:表示这是一个springboot应用
 */
@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        //返回所有加载的IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class);
        //获取所有bean的name
        String[] names = run.getBeanDefinitionNames();
        for (String n:names){
            System.out.println(n);
        }

        //注册的组件,无论获取多少次都是一个组件
        User user1 = run.getBean("user1", User.class);
        User user2 = run.getBean("user1", User.class);
        System.out.println(user1 == user2);

        MyConfig myConfig = run.getBean(MyConfig.class);
        System.out.println(myConfig);
        //如果@Configuration(proxyBeanMethods = true),此时是代理类调用获取组件的方法,springboot总会检查容器中是否有组件,有就用,没有就创建新的
        //com.study.springboot2.config.MyConfig$$EnhancerBySpringCGLIB$$10b18d19@58f174d9


        //如果@Configuration(proxyBeanMethods = false),此时每次调用方法都是创建一个新的组件
        //com.study.springboot2.config.MyConfig@69e308c6
        Pet pet = myConfig.pet();
        Pet pet1 = myConfig.pet();
        System.out.println(pet == pet1);
    }
}
  • @Import
    里面可以传入数组,用来注册bean,默认的组件名字是全类名
package com.study.springboot2.config;

import com.study.springboot2.bean.Pet;
import com.study.springboot2.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Full(proxyBeanMethods = true)
 * Lite(proxyBeanMethods = false)  轻量级
 * @Import({User.class}) 给容器自动创建出这个类型的组件
 */
@Import({User.class})
@Configuration(proxyBeanMethods = false)
//标识这是一个配置类
public class MyConfig {
    @Bean
    //给容器添加组件,默认方法名作为bean id
    public User user1(){
        return new User("111","man");
    }
    @Bean("tomtom")
    //指定beanid为tomtom
    public Pet pet(){
        return new Pet("tom");
    }
}

  • @Conditional
    条件装配:满足指定的条件,进行组件注入
    例子表示的是,只有当容器中有name为tomtom的组件时,才给user注册
    @ConditionalOnBean(name = "tomtom")
    @Bean
    //给容器添加组件,默认方法名作为bean id
    public User user1(){
        return new User("111","man");
    }

放在类名上时表示如果容器里没有指定的bean,这个类下面的所有组件都不注册

  • @ImportResource
    导入某一个资源,比如有一个xml配置文件里边写了很多bean,但是这些bean都没有被注册,此时用这个注解,写在类名上,里面指定文件路径后就可以将文件里所有的bean都注册到容器里
package com.study.springboot2.config;

import com.study.springboot2.bean.Pet;
import com.study.springboot2.bean.User;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

@ImportResource("")
@Configuration(proxyBeanMethods = false)
//标识这是一个配置类
public class MyConfig {

    @Bean
    //给容器添加组件,默认方法名作为bean id
    public User user1(){
        return new User("111","man");
    }
    @Bean("tomtom")
    //指定beanid为tomtom
    public Pet pet(){
        return new Pet("tom");
    }
}

配置绑定

想要获取配置文件里的信息
先在配置文件写数据

cat.name=12123

第一种方式:@ConfigurationProperties + @Component

使用注解@ConfigurationProperties(prefix = “cat”)获取
其中prefix 要与配置文件里的前缀保持一致
@ConfigurationProperties注解必须在容器中才能使用,所以要结合@Component

package com.study.springboot2.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "cat")
public class Pet {
    private String name;

    public String getName() {
        return name;
    }

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

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

    public Pet() {
    }

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

第二种方式:@ConfigurationProperties + @EnableConfigurationProperties

其中@ConfigurationProperties 标注方式与上面一样
@EnableConfigurationProperties必须标注在配置类上(被@Configuration修饰),指定哪个类要与配置文件绑定

package com.study.springboot2.config;

import com.study.springboot2.bean.Pet;
import com.study.springboot2.bean.User;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;

/**
 * Full(proxyBeanMethods = true)
 * Lite(proxyBeanMethods = false)  轻量级
 * @Import({User.class}) 给容器自动创建出这个类型的组件
 * @EnableConfigurationProperties(Pet.class)
 *  开启Pet与配置绑定的功能
 *  将pet这个组件自动注册到容器中
 */
@ImportResource("")
@Import({User.class})
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(Pet.class)
//标识这是一个配置类
public class MyConfig {


    @ConditionalOnBean(name = "tomtom")
    @Bean
    //给容器添加组件,默认方法名作为bean id
    public User user1(){
        return new User("111","man");
    }
    @Bean("tomtom")
    //指定beanid为tomtom
    public Pet pet(){
        return new Pet("tom");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值