Grails: Dynamically inject service in domain class

China☆狼群 提交于 2019-12-31 23:11:16

问题


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?


回答1:


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)



回答2:


IMHO domain classes shouldn't contain logic at all (apart form the validators).

In my projects I normally create a service for each domain class (e.g. UserService for class User) and I stick all the logic in there, even small bits in pieces that would normally be in the domain class.

I think a lot of programmers coming from Java/C++ world tend to find this ugly, but it suits better the Grails architecture.




回答3:


Yes. Services aren't injected into domain objects. If your domain object needs something for a particular use case, let the service that owns that use case invoke the other service on the domain object's behalf.



来源:https://stackoverflow.com/questions/2814139/grails-dynamically-inject-service-in-domain-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!