Grails的好处:使用Resource和ResourceLocator访问资源

Grails使用Spring,我们可以搭载Spring对资源加载的支持,以在应用程序的类路径中查找示例文件。 我们可以使用Spring org.springframework.core.io.Resourceorg.springframework.core.io.ResourceLoader接口在我们的应用程序中查找资源。

从Grails 2.0开始,我们还可以使用org.codehaus.groovy.grails.core.io.ResourceLocator接口。 在我们的代码中,我们可以使用实现了ResourceLocator接口的grailsResourceLocator服务。 我们必须将grailsResourceLocator服务注入我们的代码中,并使用方法findResourceForURI(String)来查找资源。 grailsResourceLocator服务的优点是它了解Grails应用程序。 例如,也可以访问插件中的资源。

首先,我们来看一个带有Resource属性和名称template Grails服务样本。 在我们的代码中,我们使用getURL()方法获取实际资源。 我们在grails-app/conf/Config.groovy设置的Resource属性的值。 我们依赖于Spring属性的自动转换,因此我们可以使用类似classpath:filename.txt的值,它将被转换为Resource实现。

package com.mrhaki.templates
 
import groovy.text.SimpleTemplateEngine
import org.springframework.core.io.Resource
 
class MessageService {
 
    Resource template
 
    String followUpMessage(final String user, final String subject) {
        final Map binding = [user: user, subject: subject]
        final SimpleTemplateEngine templateEngine = new SimpleTemplateEngine()
        templateEngine.createTemplate(template.URL).make(binding)
    }
}

grails-app/conf/Config.groovy我们定义:

...
beans {
    messageService {
        template = 'classpath:/com/mrhaki/templates/mail.template'
    }
}
...

如果使用grailsResourceLocator我们将获得以下服务实现:

package com.mrhaki.templates
 
import groovy.text.SimpleTemplateEngine
 
class MessageService {
 
    def grailsResourceLocator
 
    String template
 
    String followUpMessage(final String user, final String subject) {
        final Resource template = grailsResourceLocator.findResourceForURI(template)
        final Map binding = [user: user, subject: subject]
        final SimpleTemplateEngine templateEngine = new SimpleTemplateEngine()
        templateEngine.createTemplate(template.URL).make(binding)
    }
}

用Grails 2.2.4编写的代码

来源文章

参考: Grails优点: JDriven博客上的JCG合作伙伴 Hubert Ikkink 使用Resource和ResourceLocator访问资源

翻译自: https://www.javacodegeeks.com/2013/09/grails-goodness-accessing-resources-with-resource-and-resourcelocator.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值