application.yml:
# 服务端口设置
server:
port: 8881
# yml文件测试信息
book.name: SpringCloudInAction
book.author: ZaiYongChao
实体类:
package com.example.springboot.entity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class Book {
@Value("${book.name}")
private String name;//书名
@Value("${book.author}")
private String author;//作者
}
测试类:
@Test
public void ConfigurationTest() {
Book book = new Book();
System.out.println("书名: " + book.getName());
System.out.println("作者: " + book.getAuthor());
}
运行结果:
================
书名: null
作者: null
================
原因:不应该直接new出实体类对象,应该使用@Autowired注解注入
修改后的测试类:
@Autowired
private Book book;
@Test
public void ConfigurationTest() {
//Book book = new Book();
System.out.println("书名: " + book.getName());
System.out.println("作者: " + book.getAuthor());
}
运行结果:
================
书名: SpringCloudInAction
作者: ZaiYongChao
================