【问题标题】:Grails switching config properties based on another property loaded from a fileGrails 基于从文件加载的另一个属性切换配置属性
【发布时间】:2012-10-31 09:36:53
【问题描述】:

我不确定这是否可行,或者我是否必须找到另一种解决方法,但是......

我有一个使用 Spring-Security-Core 作为其身份验证系统的 Grails 应用程序。最终可能会在几个位置部署它,并且不同的位置可能会使用不同的身份验证提供程序(例如,有些会使用 DAO,有些会使用 LDAP 等)

我希望能够根据 .properties 文件“auth.type=LDAP”或“auth.type=DAO”中的一行来设置应用程序。一旦应用程序知道它将是两者中的哪一个,它就需要使用 Config.groovy 设置更多属性才能满足这一点。

我的想法是需要 config.groovy 从 .properties 文件加载属性,然后在 Config.groovy 中在 switch 语句中使用这些属性来确定要设置的其他属性。但是我尝试了这个,但我相信在配置文件中,来自 .properties 文件的属性是在配置文件中的所有属性之后加载的。这是一个正确的假设吗?

如果有人知道实现这种效果的简单方法,将不胜感激

【问题讨论】:

    标签: grails spring-security configuration-files


    【解决方案1】:

    您是正确的,从grails.config.locations 文件(groovy 或属性)读取的属性仅在读取主Config.groovy 后应用。您可以使用自定义环境,并拥有诸如

    之类的东西
    environments {
      ldapAuth {
        foo.bar = 'something'
      }
      daoAuth {
        foo.bar = 'something else'
      }
    }
    

    但是您必须在构建 WAR 时指定环境,不能构建一个 WAR,然后在运行时将其配置为不同的环境。

    如果您有某种方法可以为运行您的 WAR 的 tomcat(或其他)指定系统属性,那么您可以执行类似的操作

    def authType = System.getProperty('myapp.auth.type', 'dao')
    // store authType as a real config option as well as a local variable
    auth.type = authType
    
    switch(authType) {
      case 'dao':
        foo {
          bar = 'something'
        }
        break
    
      case 'ldap':
        foo {
          bar = 'something else'
        }
        break
    
      default:
        println "Unrecognised auth type ${authType}"
    }
    

    或者自己手动读取一个.properties文件(而不是依赖grails.config.locations

    def authProps = new Properties()
    new File('/etc/myapp/auth.properties').withInputStream(authProps.&load)
    def authType = authProps.getProperty('auth.type', 'dao')
    auth.type = authType
    
    // switch(authType) as before
    

    一个皱纹 - 在 log4j 闭包中,您可能会发现您无法访问 authProps 变量(我不知道,我没有尝试过)。但是在该闭包中,您可以config 访问完整的配置,因此只要您有我在上面使用过的auth.type = authType 行,您就可以改为使用config.auth.type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 2014-04-19
      • 2020-03-02
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      相关资源
      最近更新 更多