除了使用@Value注解外,还可以使用@ConfigurationProperties注解来读取application.yml配置文件中的参数。\n\n使用@ConfigurationProperties注解时,需要在配置类上添加@Component或@Configuration注解,然后使用@Value注解将配置文件中的属性值注入到对应的字段上。\n\n例如,在配置类中使用@ConfigurationProperties注解读取配置文件中的参数:\n\njava\n@Configuration\n@ConfigurationProperties(prefix = "myapp")\npublic class MyAppProperties {\n private String name;\n private int age;\n\n // getters and setters\n}\n\n\n在application.yml中配置参数:\n\nyml\nmyapp:\n name: MyApp\n age: 20\n\n\n然后在需要使用这些配置参数的地方,通过@Autowired注入配置类的实例:\n\njava\n@RestController\npublic class MyController {\n @Autowired\n private MyAppProperties myAppProperties;\n\n @GetMapping("/config")\n public String getConfig() {\n return "Name: " + myAppProperties.getName() + ", Age: " + myAppProperties.getAge();\n }\n}\n\n\n这样就可以通过myAppProperties的getter方法获取到配置文件中的参数值。

Spring Boot读取application.yml配置参数:除了@Value注解,还有@ConfigurationProperties注解

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

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