欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot读取yml或properties配置文件中的属性值

程序员文章站 2022-04-30 11:12:22
...
@Component
@ConfigurationProperties(prefix = "comment")
public class Comment {
	private String avatar;
}
comment:
  avatar: /images/avatar.png

pom.xml中加上这个包,否则@ConfigurationProperties不起作用

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

单元测试:
注意:
1.import org.junit.Test; 是这个包,而不是 import org.junit.jupiter.api.Test;
2.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BlogApplication.class)
是启动springboot的,加了这个才能用@Autowired

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BlogApplication.class)
public class Tests {


	@Autowired
	private Comment comment;

	@Test
	public void CommentTest(){
		System.out.println(comment);
		//Comment{id=null, nickname='null', email='null', content='null', avatar='/images/avatar.png', createTime=null}
	}
相关标签: 自学java