尽管对于较早版本的grails曾经问过这个问题或类似问题,但我想知道哪种方法是在现代grails 4.0.3中从grails域类中的application.yml访问配置值的最佳方法。
所以,假设我们有一个voucher.groovy

class Voucher implements HibernateEntity<Voucher> { 
  ... 
 
  Date reservedAt 
 
  static transients = ['validUntil'] 
 
  Date getValidUntil() { 
    Integer expirationTime = // TODO: fill in the configuration value 
 
    DateTime expirationDateTime = new DateTime(this.reservedAt) 
        .plusDays(expirationTime) 
        .withHourOfDay(23) 
        .withMinuteOfHour(59) 
        .withSecondOfMinute(59) 
        .withMillisOfSecond(999) 
    return expirationDateTime.toDate() 
  } 
 
} 
以及我们的 voucher.expirationTime中名为 application.yml的配置值,例如
... 
voucher.expirationTime: 10 
... 
如何在 getValidUntil()方法中访问config值?
编辑
正如@JeffScottBrown在他的评论中提到的那样,您不应访问域类中的配置值。因此,我最后使用了自定义gsp标签建议了他的建议方法。 (请参见下面的答案)

请您参考如下方法:

如何访问域类中的配置值?你不应该!
就我而言,我需要将派生值显示为域属性和配置值reservedAt + expirationTime的组合。
感谢Jeff Scott Brown的评论,我为自己的目的创建了一个自定义gsp标签:

class VoucherTagLib { 
  static returnObjectForTags = ['validUntil'] 
  static namespace = "voucher" 
 
  @Value('${voucher.expirationTime}') 
  Integer expirationTime 
 
  GrailsTagDateHelper grailsTagDateHelper 
 
  def validUntil = { attrs, body -> 
    Date reservedAt = attrs.reservedAt 
    String style = attrs.style ?: "SHORT" 
 
    Locale locale = GrailsWebRequest.lookup().getLocale() 
    if (locale == null) { 
      locale = Locale.getDefault() 
    } 
    def timeZone = grailsTagDateHelper.getTimeZone() 
 
    def dateFormat = grailsTagDateHelper.getDateFormat(style, timeZone, locale) 
 
    DateTime expirationDateTime = new DateTime(reservedAt) 
        .plusDays(expirationTime - 1) 
        .withHourOfDay(23) 
        .withMinuteOfHour(59) 
        .withSecondOfMinute(59) 
        .withMillisOfSecond(999) 
 
    return grailsTagDateHelper.format(dateFormat, expirationDateTime.toDate()) 
 
  } 
 
} 
尽管这可能不是您要找的答案,但我希望这将对其他有类似问题的人有所帮助!


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!