目录

解决办法

解决问题思路


解决办法

在相对于的控制器中使用

@EnableConfigurationProperties(AcmeProperties.class)

把属性类加载进容器中

(AcmeProperties.class是我自己项目的类名,根据自己的项目做相应修改)

 

解决问题思路

报错界面

Description:

Parameter 0 of constructor in cn.tx.sboot.controller.YamlController required a bean of type 'cn.tx.sboot.model.AcmeProperties' that could not be found.


Action:

Consider defining a bean of type 'cn.tx.sboot.model.AcmeProperties' in your configuration.

2020-11-05 14:35:38.921  WARN 7136 --- [  restartedMain] o.s.boot.SpringApplication               : Unable to close ApplicationContext

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration.class]: Unsatisfied dependency expressed through method 'springApplicationAdminRegistrar' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.env.Environment' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]

 

从问题报错的Description可以看出是由于在cn.tx.sboot.controller中构造函数的参数0。YamlController需要一个类型为“cn.tx.sboot.model.AcmeProperties”的bean。无法找到的AcmeProperties,也就是我工程目录中的AcmeProperties.class是没有被载入的到IOC容器中的

从官网https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-external-config-java-bean-binding

看出spring-boot中把属性类注入进行绑定的方式主要是使用@EnableConfigurationProperties注解来实现,不能使用@Component、@Bean和@Import等方式

 

在对应的控制器中加入

import cn.tx.sboot.model.AcmeProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableConfigurationProperties(AcmeProperties.class)
public class YamlController {



    //@Autowired
    private AcmeProperties properties1;

    public YamlController(AcmeProperties properties1) {
        this.properties1 = properties1;
    }

    @GetMapping("test")
    public AcmeProperties test(){
        return properties1;
    }


}

 

 

成功运行

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐