将服务注入到src / groovy类的实例中 [英] inject service into instance of src/groovy class

查看:120
本文介绍了将服务注入到src / groovy类的实例中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:
在src / groovy下我有许多应用程序部分创建的类(不像spring bean,而是运行时使用new()运算符)

我想为所有这些实例注入一些grails服务,是否可能以某种方式不调用构造函数或setter?

解决方案

调用构造函数和设置器是我所知的唯一执行依赖注入的两种方法。您可以使用反射并直接设置字段值,但这样可以消除在注入依赖项时执行某些逻辑的任何机会。



通常src / groovy(和src / java)类直接或间接地从可以使用依赖注入的工件(controller / service / taglib / etc)中调用,所以在那里做DI通常很简单,并将这些Spring bean传递到src / groovy类在他们的构造函数中,通过setter,或者作为使用它们的方法的参数。

显然,如果这些类是Spring bean,那么不会有问题,因为Spring会创建他们并管理依赖关系。但是,一旦你使用了一个具有bean依赖性的非bean,你必须自己去完成这项工作,或者查看一个AOP风格的解决方案,因为你需要得到某种方式的通知,那就是需要一个新的实例配置。我认为这是可行的,可能是使用AspectJ,但它可能会比它的价值更多的工作,并添加额外的魔法层,以进一步混淆新的团队成员,超出了常规的Grails和Groovy魔法。


I have the following problem: Under src/groovy I have class that is created in many parts of application (not like spring beans but in the runtime using new () operator)

I want to inject some grails services into all those instances, is it possible somehow without invoking constructor or setters?

解决方案

Invoking constructors and setters are the only two ways to do dependency injection that I know of. You can use reflection and directly set the field value, but that eliminates any opportunity of having some logic execute when a dependency is injected.

Usually src/groovy (and src/java) classes are called directly or indirectly from an artifact (controller/service/taglib/etc.) that can use dependency injection, so it's often a simple matter of doing the DI there, and passing those Spring beans to the src/groovy classes in their constructors, via setters, or as arguments of the methods that use them.

Obviously if these classes were Spring beans there wouldn't be an issue, because Spring creates them and manages dependencies. But once you are working with a non-bean that has a bean dependency, you either have to do the work yourself, or look into an AOP-style solution, since you need to be notified somehow that there's a new instance that needs to be configured. I assume that this is doable, probably with AspectJ, but it'll probably be more work than it's worth, and add an extra layer of magic to further confuse new team members beyond the regular Grails and Groovy magic.

这篇关于将服务注入到src / groovy类的实例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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