[SpringBoot 1] 自动装配和Run方法

发布时间 2023-10-01 22:11:48作者: Roy2048

SpringBoot 1


阶段:

1 SpringBoot 自动装配

build.gradle 中放依赖核心依赖, 有很多启动器(spring-boot-start-xxx)

@SpringBootApplication
    @SpringBootConfiguration
        @Configuration
            @Component
    @EnableAutoConfiguration
        @AutoConfigurationPackage
            @Import(AutoConfigurationPackages.Registrar.class)
                public void registerBeanDefinitions(AnnotationMetadata metadata
        @Import(AutoConfigurationImportSelector.class)
            public String[] selectImports(AnnotationMetadata annotationMetadata) {
                getAutoConfigurationEntry(annotationMetadata);
                    getCandidateConfigurations(annotationMetadata, attributes);
                        SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()));
                            loadSpringFactories
                                classLoader.getResources(FACTORIES_RESOURCE_LOCATION);

这里的FACTORIES_RESOURCE_LOCATION, 是写的配置路径: "META-INF/spring.factories"

所有要自动配置的类都在这个文件中(2.7之后的springboot版本中, 在另一个文件中: "META-INF/spring/%s.imports")

当然, spring中有很多第三方需要被自动装配, 但判断自动装配的注解为: @ConditionalOnXXX,是spring的底层注解, 当后面的条件都成立时, 才会被自动装配;

  • 可以在yml中设置: debug: true来查看那些类被自动装配了:

  • 普遍来说, 有一个xxxAutoConfiguration类, 导入xxxProperties类, 定制需要在yml中自己写

2 SpringBoot run方法

run方法比较复杂, 其中也运行了上面自动装配的selectImport方法

run方法的主要事项:

  1. 判断当前项目是普通项目还是web项目(是否一直运行)

  2. 查找并加载所有的初始化器, 设置到Initializer中

  3. 查找并加载所有的应用程序监听器, 设置到Listeners中

  4. 推断并设置main方法的定义类, 并设置主方法

3 yaml配置

#键值对
age: 3 # :后面必须有空格
#对象
student: #对缩进要求严格
    name: xxx
    age: 3
#行内对象
student: {name: xxx,age: 3}
#数组
students:
    - student1
    - student2
#或者: 
students: [student1, student2]

可以通过注解@ConfigurationProperties(prefix = 'student') 读取配置

  • 第二种不标准的方式: 可以指定别对名字, 然后使用SPEL表达式取值操作

写my.yaml文件

在某个配置类上写@PropertiesSource(value = 'classpath:my.yaml', factory可以指定是json还是yaml等文件的PropertySourceFactory读取类型)读取自定义的配置文件, 在类的field上写@name("$name")来取出对应的值;

  • yaml中也可以写EL表达式: 比如:
age: ${radom.uuid}# uuid值
name: ${my.name: zidingyi}#my.name存在则为第一个值, 否则为zidingyi
  • 松散绑定

yaml中写last-name, 配置中写lastName, 可以自动对应

  • JRS303数据校验

    配置类上写@Validated, field上写@NotNull之类的

    或者对于req类, 有自己的写法, 很简单搜一搜就行

  • 对于不同的环境, 可以选择激活的配置文件

    如: 有application-dev.yml, application-staging.yml

    需要使用dev环境的配置

    则在默认的applicaiton.properties/yml中指定

    spring.profiles.active=dev

  •  也可以使用---来分割不同的配置块, 在第一块中指定active的环境, 其他块中写spring.profiles=dev等(不推荐使用了)

    eg:

4 扩展或自定义WebMvcConfiguration

可方便自己实现全局的配置管理

不需要添加注解在自定义类上@EnableWebMvc

@Configuration
public MyMvcConfig implements WebMvcConfigurer {
    //可扩展自己的viewResolvers or 日期格式化Formatter etc.然后以@Bean的方式注入进来
}

5 国际化

resource目录下添加 i18npackage, 添加一个文件的name.properties, 再添加一个name_zh_CN.properties, 会自动识别成Resource Bundle, 下载插件, 就可以编辑添加多种文件。

固定配置 :application中配置 spring.messages.basename

自选配置: 自己写LocalResolver, 注入自己的MyMvcConfig使用