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

How to statically load @configurationProperties in springboot

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-05-20 23:55:04
forward
1831 people have browsed it

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;
    }
}
Copy after login
//错误2:跟第一种差不多,只是用了lombok注解代替了get\set方法,get\set也都是静态方法
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;
}
Copy after login

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;
    }
}
Copy after login
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
    public static Integer preview;

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

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template