idea中springBoot启动报错Field personProperties in com.example.controller.HelloController required a bean

本文介绍了在Spring Boot应用中使用YML配置文件时遇到的一个常见问题:在控制器中注入配置失败。文章提供了两种解决方案,并解释了导致此问题的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在读取application.yml 之后注入到HelloController 中,启动报如下错误

Field personProperties in com.example.controller.HelloController required a bean of type 'com.example.PersonProperties' that could not be found. 



有两种解决办法

第一种: 导致这个的原因是获取 .yml的属性类中没有加@Component



第二种:  当然,如果你在Application的启动类中加入了@EnableConfigurationProperties({PersonProperties.class})注解,那就不需要在PersonProperties这个类中加@Component这个注解了

 import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import ymlConfig.YmlConfig;

    @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
    @EnableConfigurationProperties({PersonProperties.class})
//没错,@EnableConfigurationProperties注解里指出的PersonProperties.class就是读取yml配置文件的类。
//@ComponentScan("")
    public class ReadApplication extends SpringBootServletInitializer{

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(ReadApplication.class);
        }

        public static void main(String[] args) {
            SpringApplication.run(ReadApplication.class, args);
        }
    }
/*
application.yml中的配置
name: 小胖

        person:
        name: 小胖
        age: 22*/

//@Component
@ConfigurationProperties(prefix = "person")
public class PersonProperties {
    private String name;
    private int age;


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值