【问题标题】:Accessing resources in Grails Plugin在 Grails 插件中访问资源
【发布时间】:2013-02-04 18:02:42
【问题描述】:

我有一个名为“foo”的 Grails 插件,它使用另一个名为“common”的 Grails 插件。

grails.plugin.location.'common' = "../common"

common”插件包含域类以及资源文件(.properties 文件、xml 模板等)。这些文件都位于 common/grails-app/conf/ 的子文件夹中。

在我的“通用”插件中有一个实现 NamespaceContext 的类,它使用这些文件来正常运行。

public class MyNamespaceContext implements NamespaceContext {

private Map<String, String> namespaces;

public MyNamespaceContext() {

    final String XML_NAMESPACES_FILE = "grails-app/conf/xml/xmlNamespaces.properties";

    try {
        Properties xmlNamespaces = new Properties();
        xmlNamespaces.load(new FileReader(XML_NAMESPACES_FILE));
        namespaces = new HashMap<String, String>((Map) xmlNamespaces);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("XML namespaces file '" + XML_NAMESPACES_FILE + "' cannot be found");
    } catch (IOException e) {
        throw new RuntimeException("IOException");
    }
}

...

}

这个类在几个类中使用,也位于形成我的域模型的“common”中,实现为 xml 装饰器。

  public class UserXmlDecorator implements User {

    private Document xmlDocument;
    private XPath xPath;
    private final String rawXml;

    public UserXmlDecorator(String rawXml) {
        this.rawXml = rawXml;
        this.xmlDocument = XmlDocumentFactory.INSTANCE.buildXmlDocumentInUTF8(rawXml);
        this.xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new MyNamespaceContext());
    }

    public String getUserName() {
        try {
            XPathExpression userNameXPathExpr = xPath.compile("...");
            String userName = userNameXPathExpr.evaluate(appendixBXmlDocument);
            return userName;
        } catch (XPathExpressionException e) {
            throw new RuntimeException();
        }
    }

    public String getAge() {
        try {
            XPathExpression ageXPathExpr = xPath.compile("...");
            String age = ageXPathExpr.evaluate(appendixBXmlDocument);
            return age;
        } catch (XPathExpressionException e) {
            throw new RuntimeException();
        }
    }

在我的 Grails 插件“foo”中创建这些装饰器时,我收到 FileNotFound 异常,因为它正在 foo/grails-app/conf/xml/xmlNamespaces.properties 中寻找模板,而不是 common/grails-app/conf/xml/xmlNamespaces.properties

我读过 Grails: How to reference a resource located inside an installed plugin? 但这对我没有帮助。

知道如何解决这个问题吗?

【问题讨论】:

  • 这似乎是一个设计问题。理想情况下,您的通用插件应该公开一个插件 foo 可以调用的方法。
  • 如果您更新帖子并添加用于加载 xml 资源的代码,这可能会有所帮助。
  • 我已经添加了相关的代码。

标签: grails plugins resources path


【解决方案1】:

通过将 .properties 文件放在类路径而不是 conf/ 目录中,然后使用类加载器加载资源来解决此问题。

xmlNamespaces.load(this.getClass().getClassLoader().getResourceAsStream(XML_NAMESPACES_FILE));

【讨论】:

    猜你喜欢
    • 2014-03-17
    • 2016-01-23
    • 1970-01-01
    • 2015-12-16
    • 2012-02-18
    • 2012-02-23
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    相关资源
    最近更新 更多