SpringBoot注記@ConfigurationProperties

4395 ワード

springbootプロジェクトごとに多くの構成があることを知っています.アプリケーション.yml,bootstrap.xmlなど.データベース接続アドレス、redisアドレス、nacos、dubbo、cloudなど、springのバージョンが何回か更新されたため、これらの構成を読み取ります.1.xml構成、xmlでbean 2を取得する.注記、@Valueなどの注記を使用して構成を取得するのが一般的です.JAva Config、java Configはspringのサブプロジェクトで、javaコードと@ConfigurationProperties注釈で構成を読み込みます.今日私が言ったのは第3の方法で、私达はこの注釈をつけて、よく使う属性はprefixで、指定した接頭辞を通じて、プロファイルの中の配置をバインドして、この注釈はクラスの上で置くことができて、方法の上で置くことができます
/**
 * Annotation for externalized configuration. Add this to a class definition or a
 * {@code @Bean} method in a {@code @Configuration} class if you want to bind and validate
 * some external Properties (e.g. from a .properties file).
 * 

* Note that contrary to {@code @Value}, SpEL expressions are not evaluated since property * values are externalized. * * @author Dave Syer * @since 1.0.0 * @see ConfigurationPropertiesBindingPostProcessor * @see EnableConfigurationProperties */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ConfigurationProperties { @AliasFor("prefix") String value() default ""; @AliasFor("value") String prefix() default ""; boolean ignoreInvalidFields() default false; boolean ignoreUnknownFields() default true; }


注記の説明から分かるように、この注記をメソッドに適用する場合、有効なバインド構成を行うには、このメソッドには@Bean注記が必要であり、所属するClassには@Configuration注記が必要である.
以下、この2つの使い方を簡単に例に挙げます.
まずアプリケーションでymlには簡単に何かを配置します
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3368/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: admin
    password: 123456

1.クラスで使用
クラスDatasourceBeanTestを新規作成します.クラスには@Componentと@ConfigurationPropertiesの注釈があります.注釈のprefixは私たちのプロファイルのプレフィックスです.
@ConfigurationProperties(prefix = "spring.datasource")
@Component
public class DatasourceBeanTest {

    private String url;

    private String username;

    private String password;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

テストクラスを書いて調整し、テストクラスにこのクラスを注入します.
@SpringBootTest
class DemoApplicationTests {
    @Autowired
    DatasourceBeanTest datasourceBeanTest;
    @Test
    void contextLoads() {
        System.out.println(datasourceBeanTest.getUsername());
        System.out.println(datasourceBeanTest.getPassword());
        System.out.println(datasourceBeanTest.getUrl());
    }
}

起動してコンソールを見ると、プロファイルが取り出されていることがわかります.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.1)

2021-01-13 18:11:43.302  INFO 8252 --- [    main] com.example.demo.DemoApplicationTests 
2021-01-13 18:11:43.311  INFO 8252 --- [    main] com.example.demo.DemoApplicationTests
2021-01-13 18:11:44.540  INFO 8252 --- [    main] o.s.s.concurrent.ThreadPoolTaskExecutor 
2021-01-13 18:11:44.855  INFO 8252 --- [    main] com.example.demo.DemoApplicationTests

admin
123456
jdbc:mysql://127.0.0.1:3368/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8

2.方法に用いる
新しいクラスCfgPropertiesTestを作成しました.このクラスでは@Configuration注記を追加しました.testDataSourceという新しい方法があります.この方法では@ConfigurationProperties注記を使用しています.
@Configuration
public class CfgPropertiesTest {
    @Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.server")
    public DruidDataSource testDataSource() {
        return new DruidDataSource();
    }
}

まとめてみると、ハ@ConfigurationPropertiesと@valueは同じ機能を持っていますが、@ConfigurationPropertiesの書き方が便利です@ConfigurationPropertiesのオブジェクトクラスの命名は比較的厳格です.prefixの接尾辞名と一致しなければならないので、値がバインドされません.特殊な接尾辞名は「driver-class-name」という横棒付きの場合です.オブジェクト内の命名規則は下線でラクダを回すとバインドに成功するので、「driverClassName」です.