2010-10-25 63 views
0

我想在Grails中添加基于Linux或基于Windows的系统属性,因为我的应用程序需要在两者中运行。我知道我们可以添加在Config中指定的grails.config.locations位置。常规。window/Linux Grails中的特定文件系统属性

但我需要if和esle条件来挑选文件。 问题是config.grrovy has userHome grailsHome appName appVersion 我需要类似osName的东西。 要么我可以继续用syetm.properties或者soembody可以告诉我,这些(只)性能如何availble的Config.groovy中(通过DefaultGrailsApplication或其他方面。这woyuld是巨大的。

此外,somewjhat MOER优雅会如果我需要这些属性,我将我的服务作为用户定义的spring-bean。这是否正确并且切实可行?如果是的话,一些示例

回答

0

你可以做这样的事情在你的Config.groovy

environments { 
    development { 
     if (System.properties["os.name"] == "Linux") { 
      grails.config.locations = [ "file:$basedir/grails-app/conf/linux.properties" ] 
     } else { 
      grails.config.locations = [ "file:$basedir/grails-app/conf/windows.properties" ] 
     } 
    } 
    ... 
} 

或者,对于基于服务的方法,您可以将所有特定于操作系统的行为捆绑到服务接口的实现中。例如:

// OsPrinterService.groovy 
interface OsPrinterService { 
    void printOs(); 
} 

// LinuxOsPrinterService.groovy 
class LinuxOsPrinterService implements OsPrinterService { 
    void printOs() { println "Linux" } 
} 

// WindowsOsPrinterService.groovy 
class WindowsOsPrinterService implements OsPrinterService { 
    void printOs() { println "Windows" } 
} 

然后实例正确的在grails-app/conf/spring/resources.groovy像这样:

beans = { 
    if (System.properties["os.name"] == "Linux") { 
     osPrinterService(LinuxOsPrinterService) {} 
    } else { 
     osPrinterService(WindowsOsPrinterService) {} 
    } 
} 

那么正确的服务将自动春天注入到你的对象。

+0

谢谢@ataylor,这就是我也想到的。加上我没有处理的bean初始化方式。另外,阅读somehwre我们可以有类似的东西,如果我们重写DefaultGrailsApplication。但文档有更多关于该插件的信息。而且我对GnG真的很陌生。独自一人。想知道是否有一种方式,否则将与if ... n其他。 – 2010-10-26 05:01:30

0

为Windows和Linux创建自定义环境。应该工作,如果放置在config.groovy

environments { 
productionWindows { 
filePath=c:\path 
} 
productionLinux { 
filePath=/var/dir 
} 
} 

你笑那么uld就可以使用grails配置对象来获取filePath在Windows或Linux上不受天气影响的值。欲了解更多详情,请参阅 的第3.2节http://www.grails.org/doc/1.0.x/guide/3.%20Configuration.html如果您想创建一个在Linux上运行的war文件,您可以执行以下命令。

grails -Dgrails.env=productionLinux war 

然后让你存储在Config.groovy中为您在运行的特定环境中的文件路径。

def fileToOpen=Conf.config.filePath 

fileToOpen将包含基于您指定文件路径在Config.groovy中的价值您当前正在运行的,所以用productionLinux运行时环境,环境也将包含值的/ var/DIR

+0

谢谢@ Jared。但我相信enviromnet {dev ....和类似的结构在run-app或war中被作为env变量传递给grails。那我怎么会通过那个。我的意思是我的问题是,如果grails为标准env做了一些更多的工作,那些不会被踢,或者如果有更好的方法来设置这个变量(productionWindows et al ..),那么而不是命令行或env。 – 2010-10-26 04:56:46

+0

请参阅我发送的链接中的“不同环境的打包和运行”部分。所以像 – Jared 2010-10-26 13:09:26

+0

我添加了更多的信息给我的答案。 – Jared 2010-10-26 13:21:04