如何在 Groovy 中使用 Spring DSL 根据环境(dev、qa、prod)注入依赖项?
我们在 Grails/Groovy 中构建了一个 Web 应用程序。在 groovy 中,我们构建了一个可插入的缓存组件,以在 Grails 应用程序中提供大型 http 响应流的缓存。我们希望根据环境在运行时注入缓存实现,例如,当开发人员在做一些本地工作时,注入一个简单的基于Map的缓存,但在操作环境中,注入一个RDBMS缓存数据库,你明白了。
我们在使用 SWITCH 的 Grails 教程中找到了这个参考,它似乎可以工作,但它丑陋且麻烦。我们有超过 5 个不同的环境(本地、开发、测试、uat 和 prod),并且需要在代码中的其他位置注入特定于环境的类,因此这种方法绝对不理想。还有其他选择吗?举例说明将不胜感激,谢谢!
//from resources.groovy
beans = {
switch(Environment.current) {
case Environment.PRODUCTION:
cacheBean(com.util.OracleCacheImpl) {
//properties here
}
break
case Environment.LOCAL:
cacheBean(com.util.MockMapCache) {
//properties
}
break
}
}
We've built a web app in Grails/Groovy. In groovy, we built a pluggable caching component to provide caching of large http response streams in the Grails app. We want to inject the cache implementation at runtime based on environment, for example, when a developer is doing some local work, inject a simple Map-based cache, but in an operational environment, inject a RDBMS cache database, you get the point.
We found this reference in the Grails tutorial which uses SWITCH, and it seems to work, but it's ugly and cumbersome. We've got over 5 different environments (local, dev, test, uat, and prod) and we need to inject environment-specific classes elsewhere in our code, so this approach is definitely not ideal. Are there any alternatives? Examples would be appreciated, thank you!
//from resources.groovy
beans = {
switch(Environment.current) {
case Environment.PRODUCTION:
cacheBean(com.util.OracleCacheImpl) {
//properties here
}
break
case Environment.LOCAL:
cacheBean(com.util.MockMapCache) {
//properties
}
break
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在
Config.groovy
中设置 bean 定义,使用其内置的environments {}
处理,并通过application
属性分配定义。因此,在
resources.groovy
中:在
Config.groovy
中:再想一想,您可能可以将整个 bean 定义放在
Config.groovy< 中/code>
Closure
并在 resources.groovy 中调用它resources.groovy
Config.groovy
You could try setting your bean definitions in
Config.groovy
, using its built inenvironments {}
handling, and assigning the definitions via theapplication
property.So in
resources.groovy
:And in
Config.groovy
:Thinking a little longer on it, you could probably put the whole bean definition in a
Config.groovy
Closure
and call it in resources.groovyresources.groovy
Config.groovy