Home  >  Article  >  Java  >  How to statically load @configurationProperties in springboot

How to statically load @configurationProperties in springboot

WBOY
WBOYforward
2023-05-20 23:55:041676browse

In normal development, we put the constants that basically do not change in configuration items, such as properties or yml files, so that they can only be loaded at startup. How to do it?

We use springboot’s @ConfigurationProperties annotation and static static corresponding properties.

But if the operation is improper, the loaded data will be empty. As for why, see the following case.

1. Error case

//错误1:get\set都是静态方法
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;

    public static Integer getPreview() {
        return preview;
    }

    public static void setPreview(Integer preview) {
        MobileConfig.preview = preview;
    }
}
//错误2:跟第一种差不多,只是用了lombok注解代替了get\set方法,get\set也都是静态方法
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;
}

2. Success case

@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;

    public static Integer getPreview() {
        return preview;
    }

    public void setPreview(Integer preview) {
        MobileConfig.preview = preview;
    }
}
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;

    public void setPreview(Integer preview) {
        MobileConfig.preview = preview;
    }
}

3. Reason

When spring is injected, it needs to call the set method. If this If the method is a static method, it cannot be dynamically injected, so you only need to add the get method to static as a static method. If @Data is used, you only need to rewrite the set method.

The above is the detailed content of How to statically load @configurationProperties in springboot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete