Springboot 中的注解 @EnableConfigurationProperties与@ConfigurationProperties


两种使用方式等价:

方式一: @Component 和 @ConfigurationProperties(prefix = "multi-tenant") 组合

package com.xx;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@Component
@ConfigurationProperties(prefix = "multi-tenant")
public class MultiTenantProperties {
    
    private String ignoreTables; //逗号分割

    private String tenantIdColumn;
}

方式二: @ConfigurationProperties 和 @Configuration,@EnableConfigurationProperties组合

package com.xx;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "multi-tenant")
public class MultiTenantProperties {
    
    private String ignoreTables; //逗号分割

    private String tenantIdColumn;
}
package com.xx;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(MultiTenantProperties.class)
public class MultiTenantConfig {
}

@ConfigurationProperties 注解,却又没有使用@Component等方式,导致无法被扫描为bean,那么就必须在@Coniguration对应配置类上使用@EnableConfigurationProperties注解去指定这个类,使得spring会扫描它,添加为bean,并识别@ConfigurationProperties注解,然后填充属性。

参考: https://www.cnblogs.com/sjkzy/p/14391304.html