在2.1.1.RELEASE中的SpringBoot中的@Value

Nuñ*_*ada 1 java spring spring-mvc spring-boot

我在application.properties文件中定义了这个值

tdk.date.format=yyyy-MM-dd'T'HH:mm:ss'.000Z'
Run Code Online (Sandbox Code Playgroud)

我在这堂课中使用的:

public class TdkDateUtils {


    private static final Logger LOG = LoggerFactory.getLogger(CryptoDateUtils.class);


    @Value("${tdk.date.format}")
    private static String tdkDateFormat;

    public static boolean afterYesterday2(String strDate) throws ParseException {

        LOG.debug("tdkDateFormat -> {} ", tdkDateFormat);

        SimpleDateFormat format = new SimpleDateFormat(tdkDateFormat);  
        Date yesterdayDate = Date.from(Instant.now().minus(1, ChronoUnit.DAYS));
        return format.parse(strDate).after(yesterdayDate);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是没有

Kar*_*cki 5

TdkDateUtils是一个实用程序类,afterYesterday2是一个静态方法.它完全存在于您的应用程序Spring上下文之外,@Value这里的注释不会被处理.

为了@Value工作,你必须制作TdkDateUtils一个bean,因为只有Spring bean会被处理PropertyPlaceholderConfigurer.或者可以在TdkDateUtils静态初始化块中自己读取和设置属性,但它违反了依赖注入的Spring哲学.