SoFunction
Updated on 2025-03-08

SpringBoot's ConfigurationProperties or Value annotation invalid problem and solution

SpringBoot's ConfigurationProperties or Value annotation is invalid

Record a question

In general SpringBoot project development, we generally create some global static configuration classes to read/config file content.

The common approach is to use the two annotations @Component and @ConfigurationProperties(prefix = "XXX") to help us implement it.

# Project related configurationcadre:
  # Name  name: cadreuc
package ;

import ;
import ;

/**
  * Global configuration class
  *
  * @author cadre
  */
@Component
@ConfigurationProperties(prefix = "cadreman")
public class Global
{
    /** Project Name */
    private static String name;

    public static String getName()
    {
        return name;
    }

    public static void setName(String name)
    {
         = name;
    }
}

The principle is very simple. Use Spring to inject attributes into static classes, and then use the static class characteristics to enable us to get its value globally in the project.

However, when we create a static class according to the cat and tiger, we find that the value we take is always null.

Is it because the Component annotation invalid? No, we will prompt the name to be repeated after creating a bean with the same name.

Is the ConfigurationProperties annotation invalid? With questions, we continue to study.

Discover the problem

As a senior CV programmer, I have not played the Get/Set method manually for many years.

But here's the problem. When we create a static property, the Get/Set methods generated by the IDE for us are all added with static by default.

	/** Project Name */
    private static String name;

	public static String getName()
    {
        return name;
    }

    public static void setName(String name)
    {
         = name;
    }
    

When Spring injects these properties, the reflected Set method will not work on the static method.

This causes our set method to not be called.

Solution

Remove the static of the Set method

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.