二、springboot配置

  1. 配置文件

    1. springboot使用一个全局的配置文件,配置文件名称是固定的;
      1. application.properties
      2. applcation.yml
    2. 配置文件的作用:修改springboot的自动配置的默认值;
      springboot在底层都给我们自动配置好了;
    3. YAML(YAML Ain·t Markup Language)
      1. YAML A Markup Language:是一个标记语言;
      2. YAML isn·t Markup Language:不是一个标记语言
    4. 标记语言:
      1. 以前的配置文件——大多都是使用XXX.xml文件;
      2. YAML:以数据为中心,比json、xml等更适合做配置文件
      3. YAML配置实例
        server:
          port: 8081
        XML:
        <server>
            <port>8081</port>
        </server>
  2. YAML语法

    1. 基本语法
      1. k:(空格)v     表示一对键值对(空格必须有);
      2. 以空格的缩进来控制层级关系;只要左对齐的一列数据,都是同一层级的
        server:
          port: 8081
          servlet:
            context-path: /dmserver
      3. 属性和值大小写敏感。
    2. 值的写法
      1. 字面量:普通的值(数值,字符串,布尔)
        字符串默认不用加上单引号或者双引号;
        “”:双引号:不会转义字符串里面的特殊字符;特殊字符会作为本身想表达的意思
                name: "zhangsan\nlisi" ->输出:zhangsan 换行 lisi
        ‘’:单引号:会转义特殊字符,特殊字符最终只是一个普通的字符串数据
                name: "zhangsan\nlisi" ->输出:zhangsan\nlisi
      2. 对象、Map(属性和值)(键值对)
        k: v:对象还是k: v的方式
        friends:
           lastName: zhangsan
           age: 20

        行内写法
        friends:{lastname: zahngsan,age: 18}
      3. 数组(List、Set)
        用- 值表示数组中的一个元素
        pets:
            - cat
            - dog
            - pig

        行内写法
        pets: [cat,dog,pig]
  3. 配置文件值注入

    1. 配置文件(yaml)
      person:
        lastName: zhangsan
        age: 18
        boss: false
        birth: 2017/12/12
        maps: {k1: v1,k2: v2}
        lists: [lisi,zhaoliu]
        dog:
          name: 小狗
          age: 2

       配置文件(properties)

      ​
      #idea properties配置文件默认使用的是utf-8
      
      person.last-name=张三
      person.age=18
      person.birth=2017/12/15
      person.boss=false
      person.maps.k1=v1
      person.maps.k2=v2
      person.lists=a,b,c
      person.dog.name=dog
      person.dog.age=15
      
      ​
    2. java bean
      /**
       * 将配置文件中的每一个属性的值,映射到这个组件中
      
       * @ConfigurationProperties:
          告诉springboot将本类中的所有属性和配置文件中相关的配置进行绑定;
      
       *  prefix = "person":配置文件中哪一个值下面的所有属性进行一一映射
       *
      
       *  只有这个组件是容器中的组件,才能使用容器提供的
          @ConfigurationProperties功能;
       */
      @Component
      @ConfigurationProperties(prefix = "person")
      public class Person {
          private String lastName;
          private Integer age;
          private Boolean boss;
          private Date birth;
      
          private Map<String,Object> maps;
          private List<Object> lists;
          private Dog dog;
      //setter,getter...
      }
      
      
      public class Dog {
          private String name;
          private Integer age;
      //setter,getter...
      }
    3. 我们可以导入配置文件处理器,以后编写配置就有提示了
              <!--导入配置文件处理器,配置文件进行绑定就会有提示-->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-configuration-processor</artifactId>
              </dependency>
    4. 从配置文件中获取值如果出现中文默认使用utf-8则会出现乱码,修改idea以下配置进行解决
    5. @Value获取值和@ConfigurationProperties获取值比较
       /**
           * <bean class="Person">
           *     <property name="lastName" value="字面量/${key}从环境变量、配置文件取值/#{spEL}"></property>
           * </bean>
           */
          @Value("${person.last-name}")
          private String lastName;
          @Value("#{11*2}")
          private Integer age;
          @Value("true")
          private Boolean boss;
       
      @ConfigurationProperties@Value
      功能批量注入配置文件中的属性一个个指定
      松散绑定(松散语法)支持不支持
      SpEL不支持支持
      JSR303数据校验支持不支持
      复杂类型注解(Map,list等)支持不支持

      配置文件yml还是properties他们都能获取到值;
      如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,就使用@Value注解;
      如果说,我们专门编写了一个JavaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

    6. 配置文件注入值数据校验
      @Component
      @ConfigurationProperties(prefix = "person")
      @Validated
      public class Person {
          /**
           * <bean class="Person">
           *     <property name="lastName" value="字面量/${key}从环境变量、配置文件取值/#{spEL}"></property>
           * </bean>
           */
          //@Value("${person.last-name}")
          @Email
          private String lastName;
          //@Value("#{11*2}")
          private Integer age;
          //@Value("true")
          private Boolean boss;
          private Date birth;
      
          private Map<String,Object> maps;
          private List<Object> lists;
          private Dog dog;
      //setter and getter ...
      }
    7. @propertySource&@ImportSource
      1. @propertySource:加载指定的配置文件
        /**
         * 将配置文件中的每一个属性的值,映射到这个组件中
         * @ConfigurationProperties:告诉springboot将本类中的所有属性和配置文件中相关的配置进行绑定;
         *  prefix = "person":配置文件中哪一个值下面的所有属性进行一一映射
         *
         *  只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能;
         *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值
         */
        @PropertySource(value = {"classpath:person.properties"})
        @Component
        @ConfigurationProperties(prefix = "person")
        @Validated
        public class Person {
            /**
             * <bean class="Person">
             *     <property name="lastName" value="字面量/${key}从环境变量、配置文件取值/#{spEL}"></property>
             * </bean>
             */
            //@Value("${person.last-name}")
            //@Email
            private String lastName;
            //@Value("#{11*2}")
            private Integer age;
            //@Value("true")
            private Boolean boss;
            private Date birth;
        
            private Map<String,Object> maps;
            private List<Object> lists;
            private Dog dog;
        //setter and getter ...
        }
      2. @ImportSource:导入Spring的配置文件,让配置文件里面的内容生效;
        SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;想让spring的配置文件生效,加载进来;@ImportSource标注在一个配置类上
        @ImportResource(locations = {"classpath:beans.xml"})
        导入spring的配置文件让其生效

        不推荐编写spring的配置文件; 

        <?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="helloService" class="cn.hymll.springboot.test1.springboottest.service.HelloService"></bean>
        </beans>

        springboot推荐给容器中添加组件的方式;推荐使用全注解的方式

        1. 配置类=====Spring配置文件

        2. 使用@Bean给容器添加组件

          /**
           * @Configuration 指明当前类是一个配置类;就是用来替代之前 spring配置文件
           *
           * 在配置文件中用<bean><bean/>标签添加组件
           */
          @Configuration
          public class MyAppConfig {
          
              //将方法的返回值添加到容器中,容器中这个组件默认的id就是这个方法名
              @Bean
              public HelloService helloService(){
                  return new HelloService();
              }
          }
  4. 配置文件占位符

    1. 随机数
      random.value,{random.int},${random.long},random.int(10),{random.int[1024,65535]}
    2. 占位符获取之前配置的值,如果没有可以使用:指定默认值
      person.last-name=张三${random.uuid}
      person.age=${random.int}
      person.birth=2017/12/15
      person.boss=false
      person.maps.k1=v1
      person.maps.k2=v2
      person.lists=a,b,c
      person.dog.name=${person.hello:hello}_dog
      person.dog.age=15
  5. Profile

    1. 多Profile文件
      我们在主配置文件编写的时候,文件名可以是  application-{profile}.properties/yml
      默认使用application.properties的配置;
    2. yml支持多文档块的方式(---的方式划分文档块)
      server:
        port: 8081
        servlet:
          context-path: /dmserver
      spring:
        profiles:
          active: dev
          #指定激活那个文本块
      ---
      server:
        port: 8083
      spring:
        profiles: dev
      ---
      spring:
        profiles: prod
      server:
        port: 8084
    3. 激活指定的profile
      1. 在配置文件中指定
        spring.profiles.active=dev
        
      2. 命令行:
        测试:--spring.profiles.active=dev

        打包运行: java -jar springboot-test-0.0.1-SNAPSHOT.jar --spring.profils.active=prod

      3. 虚拟机参数:

  6. 配置文件加载位置

    1. springboot启动hi扫描以下位置的application.properties或者application.yml文件作为Springboot的默认配置文件
      (
      优先级由高到低,高优先级的配置会覆盖低优先级的配置;
      Springboot会从这四个位置全部加载主配置文件;
      互补配置;
      )
      --file:./config
      --file:./
      --classpath:/config
      --classpath:/
    2. 我们可以通过spring.config.location改变默认的配置文件的位置
      一般是项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件一起共同起作用形成互补配置。
  7. 外部配置加载顺序

    1. springboot也可以从以下位置加载配置;优先级从高到低;高优先级配置覆盖低优先级配置;所有的配置会形成互补;
      1. 命令行参数
        java -jar springboot-config-0.0.1-SNAPSHOT.jar --server.port=8087
      2. 来自java:comp/env的JNDI属性
      3. java系统属性(system.getProperties())
      4. 操作系统环境变量
      5. RandomValuePropertySource配置的random.*属性值
      6. jar包外部的application-(profile).properties或者application.yml(带spring.profile)配置文件
      7. jar包内部的application-(profile).properties或者application.yml(带spring.profile)配置文件
      8. jar包外部的application.properties或者application.yml(不带spring.profile)配置文件
      9. jar包内部的application.properties或者application.yml(不带spring.profile)配置文件
      10. @Configuration注解类上的@PropertySource
      11. 通过SpringApplication.setDefaultProperties指定的默认属性
  8. 自动配置原理
    1. 配置文件能配置的属性参照:Common Application Properties (spring.io)
    2. 自动配置原理:
      1. SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration
      2. @EnableAutoConfiguration作用:
        1. 利用AutoConfigurationImportSelector给容器中导入一些组件;
        2. 可以插入selectImports()方法中的内容;
        3. AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
          AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
          扫描所有jar包类路径下META-INF\spring.factories
          把扫描到的这些内容包装成Properties对象
          从Properties中获取EnableAutoConfiguration.class类(类名)对应的值,然后吧他们添加到容器中
        4. 将类路径下META-INF\spring.factories里面所有的EnableAutoConfiguration的值加入到容器中
          org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
          org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
          org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
          org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
          org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
          org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
          org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
          org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\
          org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
          org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
          org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
          org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
          org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveRestClientAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
          org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
          org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
          org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
          org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
          org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
          org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
          org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
          org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
          org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
          org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
          org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
          org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
          org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
          org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
          org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
          org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
          org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
          org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
          org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
          org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
          org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
          org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
          org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
          org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
          org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
          org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
          org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
          org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
          org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
          org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
          org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
          org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
          org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
          org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
          org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
          org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
          org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
          org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
          org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
          org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
          org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
          org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
          org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
          org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
          org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
          org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
          org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
          org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
          org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
          org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
          org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
          org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
          org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
          org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
          org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
          org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
          org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
          org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
          org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
          org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
          org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
          org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

          每一个XXXAutoConfiguration类都是容器中的一个组件,用来做自动配置。

        5. 每一个自动配置类进行自动配置功能;
        6. 以HttpEncodingAutoConfiguration解释自动配置原理:
          @Configuration(
              proxyBeanMethods = false
          )//表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
          @EnableConfigurationProperties({HttpProperties.class})//启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpProperties绑定起来,并加入到IOC容器当中
          @ConditionalOnWebApplication(
              type = Type.SERVLET
          )//Spring底层是@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就生效;判断当前是否是servelet,如果是,当前注解生效
          @ConditionalOnClass({CharacterEncodingFilter.class})//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器
          @ConditionalOnProperty(
              prefix = "spring.http.encoding",
              value = {"enabled"},
              matchIfMissing = true
          )//判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的
          //即使我们配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的
          public class HttpEncodingAutoConfiguration {
              //他已经和SpringBoot映射了
              private final Encoding properties;
              //只有一个有参构造器的情况下,参数默认从容器中拿
              public HttpEncodingAutoConfiguration(HttpProperties properties) {
                  this.properties = properties.getEncoding();
              }
          
              @Bean//给容器中添加一个组件
              @ConditionalOnMissingBean//判断容器中没有这个组件
              public CharacterEncodingFilter characterEncodingFilter() {
                  CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
                  filter.setEncoding(this.properties.getCharset().name());
                  filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
                  filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
                  return filter;
              }
          }

          根据当前不同的条件判断,决定这个配置是否生效?
          一旦这个配置类生效,这个配置类就会给容器中添加各种组件,这些组件的属性是从对应的Properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的。

        7. 所有在配置文件中能配置的属性都是在XXXProperties类中封装;配置文件能配置什么就可以参照某个功能对应这个属性类
          @ConfigurationProperties(
              prefix = "spring.http"
          )//从配置文件中获取指定的值和bean的属性进行绑定
          public class HttpProperties {}

 精髓:

  1.         SpringBoot启动会加载大量的自动配置类
  2. 我们看我们需要的功能有没有SpringBoot默认写好的自动配置类
  3. 我们再来看这个自动配置类中到底配置了那些组件(只要我们要用的组件有,我们就不需要再来配置了)
  4. 给容器中自动配置类添加组件的时候,会从Properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;

 3.细节

  1.    @Conditional派生注解(Spring注解原生的@Conditional作用)
    作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置里面所有内容才生效。
  2. @Conditional扩展注解作用(判断是否满足当前指定条件)
    @ConditionalOnJava系统的java版本是否符合要求
    @ConditionalOnBean系统中存在指定Bean
    @ConditionalOnMissingBean系统中不存在指定Bean
    @ConditionalOnExpression满足SpEL表达式指定
    @ConditionalOnClass系统中有指定的类
    @ConditionalOnMissingClass系统中没有指定的类
    @ConditionalOnSingleCandidate容器中只有一个指定的bean,或者这个Bean是首选Bean
    @ConditionalOnProperty系统中指定的属性是否有指定的值
    @ConditionalOnResource类路径下是否有指定的资源文件
    @ConditionalOnWebApplication当前是Web环境
    @ConditionalOnNotWebApplication当前不是Web环境
    @ConditionalOnJndiJNDI存在指

    自动配置类必须在一定条件下才能生效

  3. 我们怎么知道那些自动配置生效?
    我们可以通过启用 debug=true属性来让控制台打印自动配置报告,这样我们可以很方便的知道那些自动配置类生效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 要配置Spring Boot与Oracle数据库的连接,需要进行以下步骤: 1. 添加Oracle JDBC驱动程序依赖项 在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>19.3.0.0</version> </dependency> ``` 2. 配置数据源 在application.properties文件中添加以下配置: ``` spring.datasource.url=jdbc:oracle:thin:@localhost:1521:ORCL spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=oracle.jdbc.OracleDriver ``` 其中,url中的localhost和1521是Oracle数据库的主机名和端口号,ORCL是数据库的SID。your_username和your_password是你的Oracle数据库的用户名和密码。 3. 测试连接 在Spring Boot应用程序中添加以下代码来测试连接: ``` @Autowired private DataSource dataSource; @GetMapping("/test") public String test() throws SQLException { Connection connection = dataSource.getConnection(); return "Connection established..."+connection.getMetaData().getDatabaseProductName(); } ``` 启动应用程序并访问/test端点,如果连接成功,则会显示“Connection established...Oracle”(假设你的Oracle数据库的名称为Oracle)。 以上就是配置Spring Boot与Oracle数据库的基本步骤。 ### 回答2: Spring Boot 是一个快速构建企业级应用程序的框架。而 Oracle 则是一个常用的企业级数据库,本文将介绍如何在 Spring Boot 中配置 Oracle 数据库。 步骤一:添加依赖 在 pom.xml 文件中添加 Oracle 的 JDBC 驱动依赖,例如: ``` <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc8</artifactId> <version>12.2.0.1</version> </dependency> ``` 步骤配置数据源 在 application.properties 文件中配置 Oracle 数据库的数据源信息,例如: ``` spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/xe spring.datasource.username=your_username spring.datasource.password=your_password ``` 其中,`driver-class-name` 指定 JDBC 驱动的类名,`url` 指定 Oracle 数据库的连接 URL,`username` 和 `password` 分别指定数据库的用户名和密码。 如果 Oracle 数据库部署在远程服务器上,则需将 `localhost` 替换为数据库服务器的 IP 地址或域名。 步骤三:启动应用程序 在 Spring Boot 应用程序中,数据库相关的 Bean 将会自动装配。可以通过在 Main 类中添加 `@SpringBootApplication` 注解来启动应用程序。 ``` @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 如果配置正确,应用程序将会启动成功并自动连接到 Oracle 数据库。 总结 通过以上三个步骤,可以快速地在 Spring Boot 中配置 Oracle 数据库,连接数据源并启动应用程序。同时也可以通过相关配置来定制数据库连接池等其他参数。 ### 回答3: Spring Boot是一种使用少量配置的快速开发框架,可帮助开发人员在短时间内创建可独立运行的Spring应用程序。在该框架中配置Oracle数据库是一个常见的需求,下面我们将介绍如何配置Oracle与Spring Boot。 1. 添加Oracle依赖 打开maven项目,找到pom.xml文件,在该文件中添加以下依赖。 ```xml <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <version>19.3.0.0</version> </dependency> ``` 在这个依赖里,我们使用Oracle官方推荐的ojdbc8驱动程序。 2. 配置Oracle数据源 在Spring Boot中,我们使用application.properties文件来配置数据源。在这个文件中添加以下内容: ```properties spring.datasource.url=jdbc:oracle:thin:@localhost:1521:ORCL spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=com.oracle.database.jdbc.driver.OracleDriver ``` 3. 测试连接 在上述步骤完成后,我们需要测试数据库是否能够成功连接。我们可以创建一个Controller类,通过在浏览器中访问该类的方法来测试连接效果。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; import java.sql.SQLException; @RestController @SpringBootApplication public class DemoApplication { @Autowired private DataSource dataSource; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping("/check") @ResponseBody String check() { try { dataSource.getConnection(); return "Database connected!"; } catch (SQLException e) { e.printStackTrace(); return "Database connection failed!"; } } } ``` 在该Controller类中,我们通过访问“/check”的方法来测试数据库是否能够成功连接,如果连接成功,将会显示“Database connected!”,否则将会显示“Database connection failed!”。 完成了以上三个步骤以后,我们就成功地将Oracle与Spring Boot进行了集成。它可以帮助我们更加便捷地开发任何适用于Oracle数据库的应用程序。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天使吻过的BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值