在 Spring Boot 中,可以使用 @ConfigurationProperties 注解加载 YML 文件中的配置并替换默认的配置。以下是具体的步骤:

  1. application.yml 文件中定义需要替换的配置项,例如:

    myapp:
      property1: 'value1'
      property2: 'value2'
    
  2. 创建一个用于加载配置的 POJO 类,例如:

    @Component
    @ConfigurationProperties(prefix = "myapp")
    public class MyAppProperties {
        private String property1;
        private String property2;
    
        // Getters and setters
    }
    
  3. 在 Spring Boot 的启动类中添加 @EnableConfigurationProperties 注解并指定需要加载的配置类,例如:

    @SpringBootApplication
    @EnableConfigurationProperties(MyAppProperties.class)
    public class MyAppApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyAppApplication.class, args);
        }
    }
    
  4. 现在,可以在其他组件中使用 @Autowired 注解将配置类注入到需要使用的地方,例如:

    @Service
    public class MyService {
        private final MyAppProperties myAppProperties;
    
        @Autowired
        public MyService(MyAppProperties myAppProperties) {
            this.myAppProperties = myAppProperties;
        }
    
        // Use myAppProperties
    }
    

    通过以上步骤,可以将 YML 文件中的配置项加载到 MyAppProperties 类中,并且可以在其他组件中使用 @Autowired 注解将其注入并使用。

SpringBoot 自动装配:使用 YML 文件配置替换默认值

原文地址: https://www.cveoy.top/t/topic/qx8b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录