Home > Mobile >  How to pass a number parameter from a properties file to a Spring annotation number (long, or int, o
How to pass a number parameter from a properties file to a Spring annotation number (long, or int, o

Time:05-20

I try to pass a number value from the Spring properties file to Annotation long properties and I wonder how to set correctly non-string parameter. I try to use the following way, and obviously, we cant define parameters with strings because of Incompatible types. Found: 'java.lang.String', required: 'long'

And my question is "How to pass a number parameter from a properties file to a Spring annotation number parameter"

application.properties

my.parameter=10

MyAnnotation.java

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {

    long myParameter() default 0;
}

MyClass.java

@Component
@MyAnnotation(myParameter = "${my.parameter}") //incompatible types long and String
public class MyClass {

//some code
}

CodePudding user response:

Here's a couple options that might work:

  1. @MyAnnotation(myParameter = "#{ T(java.lang.Long).parseLong('${email.config.port}')}")
  2. Change the value in application.properties to my.parameter=10L.

If you get the NumberFormatException after this - it means that Spring was not able to find the property.

References & useful sources:

  1. https://stackoverflow.com/a/66084308/9899739
  2. https://stackoverflow.com/a/40894656/9899739
  3. https://stackoverflow.com/a/27341777/9899739
  4. https://stackoverflow.com/a/52064355/9899739
  5. docs.spring.io, Externalized Configuration

CodePudding user response:

Your attempt will fail early at compilation phase (so, not at runtime where Spring resolves application properties), because the template ("${my.parameter}") is a string, not a long (as expected by the definition of the annotation class MyAnnotation).

A solution would be to change the type of myParameter to String, and then resolve it (when needed) using an autowired ConfigurableEnvironment from Spring.

For example:

@Component
@MyAnnotation(myParameter = "${my.parameter}")
public class FooComponent
{
    @Autowired private ConfigurableEnvironment env;

    @PostConstruct
    private void initialize()
    {
        MyAnnotation a = FooComponent.class.getAnnotation(MyAnnotation.class);
        // resolve using our application properties
        String s = env.resolvePlaceholders(a.myParameter()));
        // convert to long
        long n = Long.valueOf(s);
        // use n somehow ...
    }


    // ... more methods ...
} 
  • Related