Grails:在域中动态注入服务 [英] Grails: Dynamically inject service in domain class

查看:123
本文介绍了Grails:在域中动态注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ApplicationHolder.application .getServiceClass(package。$ {property} Service)。clazz 

注入它的相关服务。我做错了吗? 新的实例将绕过Spring的依赖管理;您需要从应用程序上下文获取配置的单例bean。改为使用它:

  def service = ApplicationHolder.application.getMainContext()。getBean($ {property} Service)

假设'property'是服务的部分bean名称,即对于FooBarService,属性会必须是'fooBar'。如果它是'FooBar',那么你可以使用GrailsNameUtils.getPropertyName()来修复它:

  import grails.util.GrailsNameUtils 

String beanName = GrailsNameUtils.getPropertyName(property)+'Service'
def service = ApplicationHolder.application.getMainContext()。getBean(beanName)


I need to inject a service based on domain property, so far I came up with the following:

ApplicationHolder.application.getServiceClass("package.${property}Service").clazz

but loading it this way doesn't inject it's dependent services. Am I doing it wrong?

解决方案

New instances will bypass Spring's dependency management; you need to get the configured singleton bean from the application context. Use this instead:

def service = ApplicationHolder.application.getMainContext().getBean("${property}Service")

That assumes that 'property' is the partial bean name for a service, i.e. for FooBarService, the property would have to be 'fooBar'. If it's 'FooBar' then you can use GrailsNameUtils.getPropertyName() to fix it:

import grails.util.GrailsNameUtils

String beanName = GrailsNameUtils.getPropertyName(property) + 'Service'
def service = ApplicationHolder.application.getMainContext().getBean(beanName)

这篇关于Grails:在域中动态注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆