springboot之尚硅谷讲课总结

yml

  1. 简介

  2. 语法

  3. 配置获取

    application.yml

    person:
      name: 小柯
      age: 16
      date: 2020/01/05
      boss: true
      maps: {k1: v1, k2: w5}
      list:
        - aa
        - bb
        - cc
        - dd
      dog:
        name: xiaogou
        age: 15

    application.properties

    person.name=小王
    person.age=100
    person.boss=false
    person.date=2020/06/05
    person.list=1,5,6,8
    person.maps.aa=123
    person.maps.bb=456
    person.dog=456

    获取(方法一)

    @ConfigurationProperties(prefix = "person")
    @Component
    public class Person {
        private String name;
        private Integer age;
        private Date date;
        private Boolean boss;
        private Map<String, Object> maps;
        private List<Object> list;
        private Dog dog;
        //getset

    获取(方法二)

    @Component
    public class Person {
        @Value("${person.name}")
        private String name;
        @Value("${person.age}")
        private Integer age;
        @Value("${person.date}")
        private Date date;
        @Value("${person.boss}")
  4. @ConfigurationProperties和@Value区别

@PropertySource和@ImportResource

  • @PropertySource加载指定位置文件

    @PropertySource(value = {"classpath:person.properties"})
    @ConfigurationProperties(prefix = "person")
    @Component
    public class Person {
        private String name;
        private Integer age;
        private Date date;
        private Boolean boss;
        private Map<String, Object> maps;
        private List<Object> list;
        private Dog dog;
        //GetSet
  • @ImportResource导入Spring的配置文件,让配置文件生效

    1、创建bean.xml
    2、创建service
    3、测试

    package springboot.io;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.ApplicationContext;
    import org.springframework.test.context.junit4.SpringRunner;
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public  class SpringbootStartApplicationTests {
        @Autowired
        ApplicationContext applicationContext;
        @Test
        public void testHelloService(){
            boolean helloService = applicationContext.containsBean("helloService");
            System.out.println(helloService);
        }
    
    }
    
    4、结果false
    5、启动类上加:@ImportResource(locations = {"classpath:bean.xml"})
    6、测试成功配置类代替
    7、springboot不推荐使用@ImportResource导入,使用全配置注入
    8、删除bean.xml、删除启动类上@ImportResource注解
    9、(方式一)创建配置类HelloConfig
            使用@Configuration和@Bean
    package springboot.io.config;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springboot.io.service.HelloService;
    import springboot.io.service.impl.HelloServiceImpl;
    @Configuration
    public class HelloConfig {
        @Bean
        public HelloService helloService(){
            return new HelloServiceImpl();
        }
    }
    
            (方式一)使用@Service

配置文件之占位符

  • 符号:${}
  • 可以写随机数{random.uuid}
  • 可以获取之前配置的值,如果没有可以设置默认值
    ${person.age:20}

配置文件之多环境

  1. 默认application.properties
  2. 使用其他环境spring.profiles.active=dev
  3. 项目启动:--spring.profile.active=dev  加入到Program arguments中
  4. 命令行:java -jar xxx.jar --spring.profile.active=dev 
  5. 虚拟机参数 -Dspring profiles.avtive=dev  加入到VM options

配置文件之加载位置

  1. 可以加载的位置(优先级由高到低,到优先级会覆盖低优先级配置,前面配置文件没有的,后面的会补上)
    file:./config   file:./  classpath:./config  classpath:./
  2. spring.config.location来改变默认的配置文件位置
    使用条件:项目打包好之后,启动项目改变默认配置文件位置,且与默认配置文件互补。
    使用方式:java -jar xxx.jar  --spring.config.location=D:/xiaoke.properties

自动配置原理

  1. 启动主配置@SpringBootApplication
  2. 开启注解:@EnableAutoConfiguration
  3. 导入@Import(EnableAutoConfigurationImportSelector.class)
    父类:AutoConfigurationImportSelector
    List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes);
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
          getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
    SpringFactoriesLoader.loadFactoryNames()扫描所有jar包类路径下META-INF/spring.factories,
    把扫描的这些文件内容包装成properties对象,封装到result中返回
  4. 获取META-INF/spring.factories
        public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
            String factoryClassName = factoryClass.getName();
    
            try {
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                ArrayList result = new ArrayList();
    
                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
                    String factoryClassNames = properties.getProperty(factoryClassName);
                    result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
                }
    
                return result;
            } catch (IOException var8) {
                throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + "META-INF/spring.factories" + "]", var8);
            }
        }
  5. 以HttpEncodingAutoConfiguration为例
     

    //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
    @Configuration
    //启动指定类,@EnableConfigurationProperties功能:将配置文件中对应的值和HttpEncodingProperties绑定起来
    @EnableConfigurationProperties(HttpEncodingProperties.class)
    //判断当前应用是否是web应用,如果是,当前配置类生效
    @ConditionalOnWebApplication
    //判断当前项目有没有这个类,CharacterEncodingFilter:springMvc中进行乱码解决的过滤器
    @ConditionalOnClass(CharacterEncodingFilter.class)
    
    //判断配置文件中是否存在某个配置,spring.http.encoding.enabled;如果不存在判断是成立的
    //即使我们配置文件中不配置spring.http.encoding.enabled = true 也是默认生效的
    @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
    public class HttpEncodingAutoConfiguration {
  6. debug = true 在控制台打印出那些自动配置类生效;

  7. 怎么解析视图的,后面慢慢理解

发布了158 篇原创文章 · 获赞 26 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_41650354/article/details/103848236