inject service into instance of src/groovy class

2019-08-25 03:26发布

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?

1条回答
Luminary・发光体
2楼-- · 2019-08-25 04:28

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.

查看更多
登录 后发表回答