Grails: Dynamically inject service in domain class

前端 未结 3 1227
独厮守ぢ
独厮守ぢ 2021-02-06 13:33

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

ApplicationHolder.application.getServiceClass(\"package.${property}Serv         


        
3条回答
  •  借酒劲吻你
    2021-02-06 14:06

    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)
    

提交回复
热议问题