Spring Boot将yaml映射为Java对象始终为null问题求助
问题原因及修复方案
1. AppProperties配置错误修复
1.1 YAML结构层级错误
你的application.yaml中将oauth2节点错误放到了app.auth层级下,但AppProperties类中auth和oauth2是平级属性,同属于app的直接子节点,同时authorizedRedirectUris的缩进层级也不正确,修改后的对应配置如下:
app: auth: tokenSecret: 04ca023b39512e46d0c2cf4b48d5aac61d34302994c87ed4eff225dcf3b0a218739f3897051a057f9b846a69ea2927a587044164b7bae5e1306219d50b588cb1 tokenExpirationMsec: 864000000 oauth2: # After successfully authenticating with the OAuth2 Provider, # we'll be generating an auth token for the user and sending the token to the # redirectUri mentioned by the client in the /oauth2/authorize request. # We're not using cookies because they won't work well in mobile clients. authorizedRedirectUris: - http://localhost:8080/oauth2/redirect
提示:YAML语法严格要求缩进必须使用空格,不能用Tab键,同级节点缩进保持一致,否则会解析失败。
1.2 配置类构造与字段错误
@ConfigurationProperties绑定要求配置类必须有可用的无参构造函数,同时绑定的字段不能用final修饰(final字段无法调用setter赋值):
@ConfigurationProperties(prefix = "app") @Data @NoArgsConstructor // 新增无参构造 public class AppProperties { // 去掉字段的final修饰符 private Auth auth = new Auth(); private OAuth2 oauth2 = new OAuth2(); @Data @AllArgsConstructor @NoArgsConstructor public static class Auth { private String tokenSecret; private long tokenExpirationMsec; } @Data @AllArgsConstructor @NoArgsConstructor public static final class OAuth2 { private List<String> authorizedRedirectUris = new ArrayList<>(); } }
2. ClientConfig配置错误修复
2.1 支持YAML格式的PropertySource
Spring默认的@PropertySource仅支持加载.properties格式文件,要加载YAML需要自定义解析工厂:
第一步:新建YAML解析工厂类
public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(resource.getResource().getFilename(), properties); } }
第二步:修改ClientConfig注解,指定自定义工厂,同时确保路径正确:
@ConfigurationProperties @PropertySource(value = "classpath:clientConfig.yaml", factory = YamlPropertySourceFactory.class) @Data public class ClientConfig { private Urls urls; @Data public static class Urls { private String user; } }
2.2 配置文件路径校验
确保clientConfig.yaml放在项目src/main/resources根目录下,和注解中配置的classpath:clientConfig.yaml路径匹配。
3. 注入方式校验
配置类必须从Spring容器中获取,不能手动new实例,正确的注入方式如下:
@Service // 或其他被Spring管理的组件类 public class YourBusinessService { @Autowired private AppProperties appProperties; @Autowired private ClientConfig clientConfig; public void testConfig() { // 此处读取的配置就不会为null System.out.println(appProperties.getAuth().getTokenSecret()); System.out.println(clientConfig.getUrls().getUser()); } }
内容的提问来源于stack exchange,提问作者roberto
相关产品推荐
相关产品推荐

