SpringBoot——2.自动装配&&实用工具&&yaml

1.自动装配

1.1 @Configuration、@Bean

在之前IOC容器中,我们如果需要构建一个bean,那么需要在XML文件中大量的写入配置信息,或者使用注解进行配置,SpringBoot当然肯定提供了方案来注入bean。

  1. 构建实体类对象

    public class Car {
        private String name;
        private String prices;
    
        public Car() {
        }
    
        public Car(String name, String prices) {
            this.name = name;
            this.prices = prices;
        }
    
        @Override
        public String toString() {
            return "Car{" +
                    "name='" + name + '\'' +
                    ", prices='" + prices + '\'' +
                    '}';
        }
    }
    
  2. 构建一个配置类,使用@Configuration来表示这是一个配置类,来集中管理所有的bean配置。在构建出bean的方法上加上@Bean注解注册到容器中,默认单例。

    @Configuration
    public class MyConfig {
    
        @Bean
        public User user() {
            return new User("1001001", 21);
        }
    
        @Bean(name = "BYD")
        public Car car1() {
            return new Car("BYD", "100000");
        }
    }
    
  3. 启动获取bean实例:

    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
    
            String[] beanDefinitionNames = run.getBeanDefinitionNames();
            for (String name : beanDefinitionNames) {
                System.out.println(name);
            }
    
            System.out.println("=------=");
    
            User user = run.getBean(User.class);
            System.out.println(user);
    
            Car car = run.getBean(Car.class);
            System.out.println(car);
        }
    }
    

    在这里插入图片描述

  4. 关于@Configuration属性proxyBeanMethods,如果proxyBeanMethods的值为true,说明bean对象会被IOC容器代理,也就是单例,如果为false,那么每次获取的值都是不同的,等于直接调用方法。

    如图,可以看出当proxyBeanMethodsfalse时,每次调用Myconfig的创建user的方法,生成的值不相同,如果为true,那么获得的就是一样的值

    在这里插入图片描述

  5. 关于通过Id获取Bean,如果@bean注解没有指明方法,那么id值默认为方法名。

proxyBeanMethods的值true或false对应两种模式Full和Lite

配置类中实例无依赖关系,可以使用Lite模式加速容器启动过程,减少判断。

配置类中实例存在依赖关系,使用Full模式。

1.2 @ComponentScan、@import

显示的使用@ComponentScan,指定扫描路径,获取路径下的bean。

@Import注解,向容器中导入自己的Bean实例或第三方实例

在这里插入图片描述

1.3 @Conditional

@Conditional注解用于条件装配,即满足@Conditional的条件,则进行注入

@Conditional有多个实现,如@ConditionalOnBean(name = "xxx’)意味当容器中存在名为xxx的实例时,才注册该实例

在这里插入图片描述

这里发现了一个问题,如果BYD写在user之前,那么可以生成user,如果写在之后,user不会生成。很坑的一点啊!

1.4 @ImportResource

虽然SpringBoot提供的Bean注解能够替代原先的xml配置,但某些场景为了兼容还是需要原先xml中配置好的Bean,由于迁移这些Bean过于麻烦,SpringBoot提供的@ImportResource注解可以直接使用原先的xml配置文件

如现有的beans.xml配置好了Bean

<?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="car01" class="com.shang.boot.bean.Car">
        <property name="name" value="DB"></property>
        <property name="prices" value="10000"></property>
    </bean>
</beans>

在这里插入图片描述

1.5 @ConfigurationProperties

使用SSM开发时,经常需要创建properties文件规定一些配置,由java代码读取并解析,如数据库连接需要password、port等,这个过程如果使用原生Java来处理需要涉及流处理,但在SpringBoot中只需使用@ConfigurationProperties即可快速完成.

如新建实例Car,使用@component注解将其作为组件加入容器,并使用@ConfigurationProperties注解指明key前缀

在这里插入图片描述

application.properties文件中这样以K-V的形式进行定义。

在这里插入图片描述

在这里插入图片描述

1.6 配置小结

1,SpringBoot启动前会先加载所有的自动配置类
2,每个自动配置类按照条件选择性生效,默认绑定配置文件(如ServerProperties)指定的值
3,生效的配置类会给容器中增加许多实例
4,只要容器中有这些注册好的实例,相当于这些功能可以直接使用
5,只要有用户自己配置的,以用户配置的优先,用户直接@Bean替换默认实例或修改配置文件(application.properties)

2.实用工具

2.1 Lombok

简化业务对象开发,省略构造器,get/set方法,toString方法等。不需要在源代码中写这些了,具体的实现会在编译时生成。

maven引入依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-->SpringBoot已经声明了版本<-->

编写对象类

@AllArgsConstructor //生成全参方法
@NoArgsConstructor //生成无参方法
@Data //生成get/set方法
@ToString //生成tostring方法
@Component //注入到容器
public class User {
    private String name;
    private int age;
}

查看class文件,确实生成了

在这里插入图片描述

还可以使用Lombok中的@Slf4j作为日志功能

2.2 Developer-Tools

开发中经常需要修改代码或配置,但每次修改完后都需要重新启动
为此可以使用Developer-Tools,引入依赖:

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

本质还是重新启动,修改代码后使用Ctrl + f9实现更新。

2.3 Spring Initializr

通过Spring Initializr更快的构建SpringBoot工程

在这里插入图片描述

在这里插入图片描述

勾选需要的功能

在这里插入图片描述

完成

在这里插入图片描述

3. yaml配置文件

4.1 yaml使用

yaml是一种标记语言,用法类似properties,非常适合用于以数据为中心的配置文件

yaml基本语法:

1.key: value;kv之间有空格
2.大小写敏感
3.使用缩进表示层级关系
4.缩进不允许使用tab,只允许空格
5.缩进的空格数不重要,只要相同层级的元素左对齐即可
6.'#'表示注释
7.字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义

4.2 数据类型

字面量:单个的、不可再分的值。date、boolean、string、number、null
	k: v
对象:键值对的集合。map、hash、set、object 
	行内写法:  k: {k1:v1,k2:v2,k3:v3}
	#或
	k: 
		k1: v1
  		k2: v2
  		k3: v3
数组:一组按次序排列的值。array、list、queue
	行内写法:  k: [v1,v2,v3]
	#或者
	k:
 		- v1
 		- v2
 		- v3

使用yaml表示一个Persion类实例

@Data //生成get&set
@Component //注入到容器
@ConfigurationProperties(prefix = "person") //指定配置信息头
public class Person {
    private String name;
    private Integer age;
    private Date birth;
    private List<Pet> pets;
    private Map<String, Object> score;
}

@Data
@ToString
public class Pet {
    private String name;
    private Integer age;
}

yaml配置
person:
  name: zhangsan
  sex: true
  age: 21
  birth: 2001/04/25
  pets:
    - {name: hh, age: 12}
    - {name: ww, age: 23}
  score:
    english: 80
    math: 90

注意:

  • yaml文件名为:application.yaml
  • 如果值被双引号引起来,那么值如果存在转义字符,会被转义,单引号则不会被转义
  • yaml常用于默认配置,properties常用于上线使用,因为properties优先级大于yaml

4.3 yaml文件自动提示

第一次使用yaml时,会发现没有提示,不像application.properties文件一样便捷,为此可以引入依赖

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

重启之后,yaml编写即可出现提示

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值