以前,我定义属性值都是在application开头的配置文件的,有一天自定义了一个配置文件名为ldj.properties.结合注解 @PropertySource 指定加载读取它,然后@EnableConfigurationProperties测试发现,使用的都是默认值,没有读取配置的值.
package com.dj.springtest.config.properties;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* User: ldj
* Date: 2023/7/14
* Time: 23:27
* Description: No Description
*/
@Data
//@Component("test") //直接然容器扫描成为Bean 成功
@PropertySource(value = "classpath:ldj.properties")
@ConfigurationProperties(prefix = "spring.test.config")
public class TestConfigProperties {
private String name = "ldj";
private Integer age = 18;
//@ConfigurationProperties和 @Value 可以兼容的
@Value("${demo.test.gender:女}")
private String gender;
}
package com.dj.springtest.config;
import com.dj.springtest.config.properties.TestConfigProperties;
import com.dj.springtest.service.TestService;
import com.dj.springtest.service.TestServiceImpl;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* User: ldj
* Date: 2023/7/14
* Time: 23:28
* Description: No Description
*/
@Data
@Configuration
//@Import(value = {TestConfigProperties.class}) //直接当普通类导入成Bean 成功,默认也是先从bootstrap,application开头的文件获取,没有再从ldj.properties获取
@EnableConfigurationProperties(value = {TestConfigProperties.class}) //失败!! 属性值必须配置在application或者bootstrap开头文件才可以
public class TestConfig {
@Bean
@ConditionalOnMissingBean(TestService.class)
public TestServiceImpl testService(TestConfigProperties properties) {
return new TestServiceImpl(properties.getName(), properties.getAge());
}
}