idea中springBoot启动报错Field personProperties in com.example.controller.HelloController required a bean
在读取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;