Java – Whether the type/class needs to be annotated with @Component or @Service in order to annotate its properties using @Value

Whether the type/class needs to be annotated with @Component or @Service in order to annotate its properties using @Value… here is a solution to the problem.

Whether the type/class needs to be annotated with @Component or @Service in order to annotate its properties using @Value

We have the following code, which works for us, and we can set the visible value via application.properties

public enum Checker {
  RED ("#FF0000"),
  YELLOW ("#FFFF00");

private final String value;

@Value("${visible:true}")
  private String visible;

private Checker(final String value) {
    this.value = value;
  }

public String getValue() { 
    if (visible) {
      return value; 
    }
    else {
      return "#000000";
    }
  }
}

Now, to better understand it, shouldn’t the bean be initialized before it can be injected?

Solution

The answer is yes, but not exactly. The correct statement is that a class instance needs to be a spring bean to be a @Value to work. Add @Component, @Service make the class a spring-managed bean, but there are other methods that use @Bean.

In normal spring work, by using processor to change or add functionality to your declared beans, as with @Transactional, @Value will only take effect if it is a bean, yes, you can comment any method in any class, the code will compile, but spring Will simply not consider it.

From @Value documentation

Note that actual processing of the @Value annotation is performed by a
BeanPostProcessor

Related Problems and Solutions