使用yaml给springboot绑定数据时常见问题

本文讲述了在使用Spring Boot应用过程中,如何解决配置文件中people类实体与yaml文件的绑定错误,涉及数据结构不匹配、属性格式错误及控制器注解问题,最终通过调整实体类和yaml配置实现正确启动。
摘要由CSDN通过智能技术生成

下面是我实体类配置

@Component
@ConfigurationProperties(prefix = "people")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class people {
    private int id;
    private String name;
    private Date birth;
    private Boolean boss;
    private Integer age;
    private pet pet;
    private String[] interests;
    private List<String> animals;
    private Map<String,Integer> scores;
    private Set<Double> salarys;
    private Map<String,List<pet>> allpets;
}
@Component
public class pet {
    private int id;
    private String name;
}

下面是我yaml文件配置

people:
  id: 1001
  name: gn
  birth: 2000/1/1
  boss: true
  age: 22
  pet:
    id: 001
    name: gn
#  interests: [篮球,足球]
  interests:
    - 篮球
    - 足球
  animals: [cat,dog]
  scores: [english:80,math:90]
  salarys:
    - 9999.99
    - 9999.98
  allpets:
    sick:
      - {id: 2,name: sd}
      - id: 3
      name: ad
    health:
     - {id: 004,name: ad}
     - {id: 005,name: fs}

controller层

@Controller
public class firstController {
    @Autowired
    com.springbootlearn2.pojo.people people;
    @RequestMapping("/people")
    public people peoplecontroller(){
        return people;
    }
}

然后我们来执行

出现了下列错误

15:56:51.584 [Thread-1] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@9ca2293
15:56:51.959 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
org.yaml.snakeyaml.parser.ParserException: while parsing a block collection
 in 'reader', line 21, column 7:
          - {id: 2,name: sd}
          ^
expected <block end>, but found '?'
 in 'reader', line 23, column 7:
          name: ad
          ^

报错位置在21,跟23行,我们检查后发现原因是我们少了一个 - 而且没有对齐

 我们修改如下

allpets:
    sick:
      - {id: 2,name: sd}
      - id: 3
        name: ad
    health:
     - {id: 004,name: ad}
     - {id: 005,name: fs}

再次执行,依然报错

APPLICATION FAILED TO START
***************************

Description:

Binding to target [Bindable@6a4d645 type = java.util.List<com.springbootlearn2.pojo.pet>, value = 'none', annotations = array<Annotation>[[empty]]] failed:

    Property: people.allpets.sick[0].id
    Value: 2
    Origin: class path resource [application.yaml] - 21:14
    Reason: The elements [people.allpets.sick[0].id,people.allpets.sick[0].name,people.allpets.sick[1].id,people.allpets.sick[1].name] were left unbound.
    Property: people.allpets.sick[0].name
    Value: sd
    Origin: class path resource [application.yaml] - 21:22
    Reason: The elements [people.allpets.sick[0].id,people.allpets.sick[0].name,people.allpets.sick[1].id,people.allpets.sick[1].name] were left unbound.
    Property: people.allpets.sick[1].id
    Value: 3
    Origin: class path resource [application.yaml] - 22:13
    Reason: The elements [people.allpets.sick[0].id,people.allpets.sick[0].name,people.allpets.sick[1].id,people.allpets.sick[1].name] were left unbound.
    Property: people.allpets.sick[1].name
    Value: ad
    Origin: class path resource [application.yaml] - 23:15
    Reason: The elements [people.allpets.sick[0].id,people.allpets.sick[0].name,people.allpets.sick[1].id,people.allpets.sick[1].name] were left unbound.

看起来错的很多,别慌,这种情况一般是配置错误,我们检查yaml问题之后没什么问题,那么问题应该在实体类里面,这里我们发现了问题,我们仅仅配置了

@Component这个仅仅能配置到组件里面,我们没有配置lombok,修改如下

@Data
@ToString
public class pet {
    private int id;
    private String name;
}

再次运行

Failed to bind properties under 'people.scores[0]' to java.lang.Integer:

    Property: people.scores[0]
    Value: english:80
    Origin: class path resource [application.yaml] - 15:12
    Reason: failed to convert java.lang.String to java.lang.Integer (caused by java.lang.NumberFormatException: For input string: "english:80")

Action:

发现是scores出了问题,{}错误用成了[]

  scores: {english:80,math:90}

修改后继续运行

 :: Spring Boot ::                (v2.6.3)

2022-02-24 16:33:55.665  INFO 27724 --- [  restartedMain] c.s.Springbootlearn2Application          : Starting Springbootlearn2Application using Java 1.8.0_121 on LAPTOP-T8R1BEM0 with PID 27724 (D:\study\java\IDEA\springboot\learn2\target\classes started by li in D:\study\java\IDEA\springboot\learn2)
2022-02-24 16:33:55.666  INFO 27724 --- [  restartedMain] c.s.Springbootlearn2Application          : No active profile set, falling back to default profiles: default
2022-02-24 16:33:55.722  INFO 27724 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-02-24 16:33:55.722  INFO 27724 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-02-24 16:33:56.612  INFO 27724 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-02-24 16:33:56.620  INFO 27724 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-02-24 16:33:56.620  INFO 27724 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-02-24 16:33:56.720  INFO 27724 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-02-24 16:33:56.721  INFO 27724 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 998 ms
2022-02-24 16:33:56.970  INFO 27724 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-02-24 16:33:56.993  INFO 27724 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-02-24 16:33:57.001  INFO 27724 --- [  restartedMain] c.s.Springbootlearn2Application          : Started Springbootlearn2Application in 1.801 seconds (JVM running for 4.009)

没有问题,那么我们开始在网页查看

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Feb 24 16:36:52 GMT+08:00 2022
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [people]: would dispatch back to the current handler URL [/people] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
javax.servlet.ServletException: Circular view path [people]: would dispatch back to the current handler URL [/people] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
	at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:210)
	at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:148)
	at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
	at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1401)
	at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
	at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)

又是铺天盖地的错误,别慌,还是那句话,如果前面没有错误,那么这种海量错误往往是配置问题,这是500错误,重点是 Check your ViewResolver setup!这个错误,这是ViewResolver问题,也就是返回值的错误

我们修改@Controller为@RestController

@RestController是

@Controller
@ResponseBody

的符合注解

我们执行

 正常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值