且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Grails:在域中动态注入服务

更新时间:2023-02-26 19:19:29

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)