1

I have a config.properties file:

date_format="yyyy-MM-dd"

My springmvc-servlet.xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config/config.properties</value>
        </list>
    </property>
</bean>

This is my controller class:

@Controller
@RequestMapping("/T")
public class Test extends BaseController
{
    @Value("${date_format}")
    private static final String format; // Here, I want a final String as a constant

    @RequestMapping(value = "t2")
    @ResponseBody
    public String func(@RequestParam("date") @DateTimeFormat(pattern = format) Date date)
    {
        return date.toString();
    }
}

I want to use @Value annotation on a final variable, which is used in the annotation @DateTimeFormat.

@DateTimeFormat requires a final String variable, this is why I need to use @Value on final variables. But it doesn't work currently. Any ideas?

Chip Zhang
  • 641
  • 2
  • 11
  • 26
  • Is your date format changing so often that you need to have it configurable in a properties file? – Sotirios Delimanolis Jan 15 '15 at 02:50
  • Why would you want to inject into a static field? See http://stackoverflow.com/questions/10938529/why-cant-we-autowire-static-fields-in-spring for reasons not to do this. – mkobit Jan 15 '15 at 04:27

1 Answers1

0

I answered a question like this https://stackoverflow.com/questions/7130425...

I'd remove the static modifier and do something similar to this:

@Controller
@RequestMapping("/T")
public class Test extends BaseController{

   @Value("${date_format}")
   private final String format; // Removed static

   public Test (@Value("${date_format}") format){
     this.format = format;
   }

   @RequestMapping(value = "t2")
   @ResponseBody
   public String func(@RequestParam("date") @DateTimeFormat(pattern = format) Date date){
     return date.toString();
   }
}

This is known as Constructor Injection.

Austin Poole
  • 652
  • 6
  • 11