@ConfigurationProperties 注解失败

springboot 使用httpinvoker 报错:

pom文件

img

客户端配置

img

yml配置项对应实体

img

yml配置

img

在启动时 yml中配置项并未加载成功

img

用测试类却可以加载成功

img

请问什么原因啊?

在使用 httpinvoker 时,如果在 @ConfigurationProperties 注释的类中使用 @Autowired 注释注入其他 Bean,则可能会遇到此错误。这是由于 @ConfigurationProperties 注释的类是在 ApplicationContext 加载时创建的,但是在 ApplicationContext 加载之前,其他 Bean 尚未创建。因此,如果在 @ConfigurationProperties 注释的类中使用 @Autowired 注释注入其他 Bean,则可能会出现 NullPointerException 或其他错误。要解决此问题,请尝试使用构造函数注入或将 @Autowired 注释移到另一个类中。例如:

@Configuration
@EnableConfigurationProperties(MyProperties.class)
public class MyConfiguration {

    private final MyBean myBean;

    public MyConfiguration(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyService myService(MyProperties properties) {
        // 使用 MyBean 和 MyProperties 创建 MyService
        return new MyService(myBean, properties);
    }
}

@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@Component
public class MyBean {
    // ...
}

@Service
public class MyService {

    private final MyBean myBean;
    private final MyProperties properties;

    public MyService(MyBean myBean, MyProperties properties) {
        this.myBean = myBean;
        this.properties = properties;
    }

    // ...
}

在此示例中,MyConfiguration 类使用构造函数注入 MyBean,然后使用 MyBeanMyProperties 创建 MyServiceMyProperties 类与 @ConfigurationProperties 注释一起使用,以从 application.properties 中读取属性。 MyBean 类是一个简单的 Bean,用于演示如何在 MyConfiguration 中注入其他 Bean。请注意,MyService 类使用构造函数注入 MyBeanMyProperties,而不是在 @Autowired 注释字段上使用。

如果您仍然遇到问题,请尝试在 @ConfigurationProperties 注释的类中使用 @PostConstruct 注释标记一个方法,并在该方法中执行任何需要其他 Bean 的初始化逻辑。这将确保在 @ConfigurationProperties 注释的类中使用其他 Bean 时,这些 Bean 已经初始化并准备好使用。例如:

@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private String name;

    @Autowired
    private MyBean myBean;

    @PostConstruct
    public void init() {
        // 在这里使用 MyBean 进行初始化逻辑
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在此示例中,使用 @Autowired 注释将 MyBean 注入 MyProperties 中,然后使用 @PostConstruct 注释标记一个方法,该方法将使用 MyBean 执行初始化逻辑。这将确保在 MyProperties 中使用 MyBean 时,MyBean 已经初始化并准备好使用。

请注意,@Autowired@PostConstruct 注释都需要 Spring 框架的支持。如果您使用的是其他框架或库,则可能需要使用不同的技术来解决此问题。

是不是一些配置类没有被扫描到。