【问题标题】:Java Records are not working with ConfigurationProperties annotationJava 记录不适用于 ConfigurationProperties 注释
【发布时间】:2022-01-01 21:29:00
【问题描述】:

我正在使用@ConfigurationProperties 注释来自动配置我的属性。在我的配置类工作正常之前,但我试图用记录实现同样的事情,但失败了。

我一直在关注这个 SO 答案,但在我的情况下它不起作用:https://stackoverflow.com/a/68358180/13189473

在我的application.properties 中有一个属性是cache.validity=200

这是代码

@Component
@ConfigurationProperties("cache")
public record MyConfig(int validity) {

    @ConstructorBinding
    public MyConfig(int validity) {
        this.validity= Optional.ofNullable(validity).orElse(0);
    }
}

当我尝试启动我的应用程序时,我收到以下错误:

Description:

Parameter 0 of constructor in ...MyConfig required a bean of type 'int' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'int' in your configuration.

完成这项工作的正确方法是什么?提前致谢。

编辑: 我的 pom.xml:

    <properties>
        <java.version>17</java.version>
        <spring.boot.version>2.5.4</spring.boot.version>
        <spring.version>5.3.9</spring.version>
    </properties>

我的 application.properties:

server.port=8060
cache.validity=0

... (DB Drivers/Security Configs)

【问题讨论】:

    标签: java spring record spring-autoconfiguration


    【解决方案1】:

    好吧,我想通了:)

    此外,重要的是要强调使用构造函数 绑定,我们需要显式启用我们的配置类 使用 @EnableConfigurationProperties 或使用 @ConfigurationPropertiesScan。

    下面使用 SpringBoot 2.5.4 和 Java 17 的工作示例:

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
    
    @SpringBootApplication
    @ConfigurationPropertiesScan
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }
    

    package com.example.demo;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.ConstructorBinding;
    
    @ConfigurationProperties("cache")
    @ConstructorBinding
    public record ExampleRecordConfig(int validity) {
    }
    

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ServiceWhichUsesConfig {
    
        @Autowired
        private ExampleRecordConfig exampleRecordConfig;
    
    
        public void justChecking(){
            System.out.println(exampleRecordConfig.validity());
        }
    
    }
    

    package com.example.demo;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class DemoApplicationTests {
    
        @Autowired
        private ServiceWhichUsesConfig serviceWhichUsesConfig;
    
        @Test
        void contextLoads() {
            serviceWhichUsesConfig.justChecking();
        }
    
    }
    

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.5.4</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    什么使它起作用:@ConfigurationPropertiesScan

    === 已编辑 ===

    只是为了好玩,回答您有关默认值的问题。您可以通过以下方式实现它:

    这样做的缺点是您默认使用代码,而不是配置。

    @ConfigurationProperties("cache")
    @ConstructorBinding
    public record ExampleRecordConfig(Integer validity) {
    
        public Integer validity(){  <-- notice the name..it cant be getValidity()
            if(validity != null)
                return validity;
            return 500;
        }
    }
    

    如果您的属性文件中根本没有定义cache.validity,那么它将返回500



    对于配置文件默认值,您需要以不同的方式进行:

    somePropertyEitherFromEnvironmentOrAlreadyDefinedUpInProperitiesFile=5
    server.port=8060
    cache.validity=${somePropertyEitherFromEnvironmentOrAlreadyDefinedUpInProperitiesFile:5000000}
    

    然后它将打印5,因为第一个somePropertyEitherFromEnvironmentOrAlreadyDefinedUpInPrope 有一个值。


    server.port=8060
    cache.validity=${somePropertyEitherFromEnvironmentOrAlreadyDefinedUpInProperitiesFile:5000000}
    

    如果没有定义somePropertyEitherFromEnvironmentOrAlreadyDefinedUpInPrope,它将打印默认的5000000

    【讨论】:

    • 不幸的是同样的错误
    • 我将尝试在本地复制它,@MrNobody 让你更新
    • 回复@MrNobody 一切皆有可能:)
    • 请告诉我这是否有意义@MrNobody 否则我可以重写它以便更容易理解
    • 是的,这很有意义,非常感谢您的清晰而轻松的工作:)
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2020-07-02
    相关资源
    最近更新 更多