一个注解搞定配置文件的读取(springboot)

注解:@ConfigurationProperties

 1、新建与配置文件对应的实体类,并放入spring容器中

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

@Data
@Component
@ConfigurationProperties(prefix = "river")
public class AppConfig {
    private String name;
}

2、配置application.yml文件

river:
  name: engineerdong

3、在需要的地方注入并使用

@Slf4j
@SpringBootTest
class RiverApplicationTests {

    @Autowired
    AppConfig config;

    @Test
    void logSomething() {
        log.error(config.getName());
    }
}

 打印:

com.boot.river.RiverApplicationTests 2020年01月10日 18:48:21 -- engineerdong

补充:

如果idea编辑器报了如下错误:

springboot Configuration Annotation processor not found in classpath

加入如下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

关于@Data的使用,可以参考:https://blog.csdn.net/river66/article/details/103727367

关于@Slf4j的使用,可以参考:https://blog.csdn.net/river66/article/details/103713397

觉得有用的老铁点个赞呗~

发布了78 篇原创文章 · 获赞 131 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/river66/article/details/103929335