java - Spring MVC : @Value annotation with final variable

标签 java spring spring-mvc servlets

我有一个 config.properties 文件:

date_format="yyyy-MM-dd"

我的 springmvc-servlet.xml:

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

这是我的 Controller 类:

@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();
    }
}

我想在最终变量上使用@Value注释,该变量在注释@DateTimeFormat中使用。

@DateTimeFormat 需要一个最终的字符串变量,这就是为什么我需要在最终变量上使用@Value。但目前还不起作用。有什么想法吗?

最佳答案

我回答了这样的问题 https://stackoverflow.com/questions/7130425...

我会删除 static 修饰符并执行类似的操作:

@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();
   }
}

这被称为Constructor Injection .

关于java - Spring MVC : @Value annotation with final variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955791/

相关文章:

java - 如何使用@EntityListeners记录@Entity更改?

java - 如何将泛型参数绑定(bind)到特定的List子类?

spring - 找不到Elasticsearch Spring JSONObject [“hits”]

java - 如何以编程方式检索所有 antmatcher URL

spring - 我可以将两个 spring Controller 链接在一起,每个都对页面的数据进行部分检索吗?

java - 以日期为数据类型将字符串转换为 "yyy-MM-dd"格式

java - Spring模板Hello world项目不起作用

java - 正则表达式:忽略组的顺序

java - 禁用 Springboot RSocket 项目的 "default"Netty 端口

java - Spring+Hibernate+JPA的多数据库