【问题标题】:access configuration/property files from src/groovy从 src/groovy 访问配置/属性文件
【发布时间】:2014-09-04 07:53:02
【问题描述】:

我在 src/groovy 下有一个文件,我的 Config.groovy 和外部属性文件中也有一些属性。通常,如果想要访问属性,可以使用 grailsApplication .configuration.property.name 表达式。我希望能够从 src/groovy 目录下的这个文件中访问所有这些属性。到目前为止我所尝试的

import grails.util.Holders

class ForkedTomcatCustomizer {

    def application

    void customize(Tomcat tomcat) {

        println Holders.grailsApplication.config.property.name
    }
}

给我 NPE 说 grailsAppliction 为空

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA



class ForkedTomcatCustomizer {

    def application

    void customize(Tomcat tomcat) {

        def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
        def grailsAppliction = ctx.grailsApplication.getObject()
        println grailsAppliction.config.property.name
    }
}

相同 - NPE,因为 grailsAppliction 为空

是否有可能以某种方式处理这种情况?谢谢!

【问题讨论】:

    标签: grails grails-2.0 grails-plugin


    【解决方案1】:

    使用下面的,看看它是否有效

    println Holders.config.property.name
    

    使用 Holders 时不需要 grailsApplication。

    【讨论】:

    • 不幸的是,这也给了 NPE。说配置对象为空
    • @AndreyYaskulsky - 这很奇怪!我一直在我的 src 文件中使用它,它非常适合我。我正在使用 grails 2.1.2,不确定但可能与版本有关
    • 我的猜测是他试图在配置构建之前访问它,例如在构建期间
    • @LalitAgarwal 我正在使用不同的 - 2.4.2
    • @Dónal 是的,看起来,是否可以从此类中强制加载配置?
    【解决方案2】:

    下面的示例可能比您需要的要复杂一些,但它们展示了如何在构建时获取配置属性。我使用它们来合并两个配置文件,但您可能不需要这样做。

    当在 CompileEnd 事件中调用 here 时,此 method 返回一个配置属性。

    您可以在应用的 _Events.groovy 文件中定义一个类似的方法来调用您自己的配置持有者类。

    【讨论】:

      【解决方案3】:
      import org.codehaus.groovy.grails.commons.ConfigurationHolder;
      
      class KeyAndSecret{
           public static String consumerKey = ConfigurationHolder.config.consumerKey;
           public static String consumerSecret = ConfigurationHolder.config.consumerSecret;
      }
      

      这样试试

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        • 2017-05-06
        • 2015-03-22
        • 2020-06-05
        • 1970-01-01
        • 2017-12-13
        • 1970-01-01
        相关资源
        最近更新 更多