springannotationsspring-3

how to use @value annotation inside a method to read a a property from property file?


Can i use @value annotation inside a method to read property?

    void method1(){

     @Value("#{AppProperties['service.name']}") String name;
     -------
      -------
   } 

Solution

  • accessor private for a method variable is unappropriate.

    If you look at the definition of @Value annotation, it can only be placed FIELD, PARAMETER or METHOD level.

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Value {
    

    So either you declare name as a class attribute or as a method parameter...