业务功能描述:读取yaml配置中的user对象,将该对象的属性显示在网页上(尚硅谷spring全家桶146集)
我的问题是:gfs属性一直为null
controller文件:
package com.atguigu.controller;
import com.atguigu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private User user;
@GetMapping("show")
public User show(){
return user;
}
}
User实体类:
package com.atguigu.pojo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 读取配置的方式1:@Value
* 直接在属性上添加
* @Value(key必须写全)
* @Value只能读取单个值
* 批量配置读取:
* @ConfigurationProperties(prefix="zwf.user")通用前缀
* 优势:方便批量读取数据;可以给集合类型赋值
*/
@Data
@Component
@ConfigurationProperties(prefix="zwf.user")
public class User {
// @Value("${zwf.user.username}")
private String username;//只要zwf.user.属性名=key,那么配置文件的value会被自动赋值给属性
// @Value("${zwf.user.password}")
private String password;
// @Value("${zwf.stars}")
private List<String> gfs;
}
yaml配置:
server:
port: 8080
servlet:
context-path: /boot
zwf:
user:
username: root
password: 123456
gfs:
- a
- b
- c
原因是:在yaml配置文件中依靠缩进来表示属性之间的层级关系,我在写的时候把gfs设置了跟user同一个层级,同时实体类的@ConfigurationProperties(prefix="zwf.user")注解中设置了扫描前缀是zwf.user,此时内部的组件检测不到zwf.gfs下的数据,因此user的gfs属性显示为null
解决办法:把gfs放在user的下一个层级
server:
port: 8080
servlet:
context-path: /boot
zwf:
user:
gfs:
- a
- b
- c
其他解决思路:查看@ConfigurationProperties的前缀/后缀是否包含你需要被扫描到的数据的层级,检查是否把user实体类加入到ioc容器,检查是否添加@ConfigurationProperties注解/@Value注解(需要注意的是,@Value注解不能为集合数据赋值,当需要为集合数据赋值时,建议使用@ConfigurationProperties(prefix="xxx.xxx"))