Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Spring bean *not* by dependency injection

We have some domain objects that are created at runtime - not by Spring. These domain objects need access to some service type beans that are being managed by Spring. How can the domain objects that are created at runtime access Spring beans dynamically (not by DI)?

like image 926
Marcus Leon Avatar asked Nov 28 '09 22:11

Marcus Leon


People also ask

Which injection is not supported in Spring dependency injection?

With setter injection, Spring allows us to specify optional dependencies by adding @Autowired(required = false) to a setter method. This is not possible with constructor injection since the required=false would be applied to all constructor arguments.

What is the difference between @inject and @autowired?

@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application. Sr.


1 Answers

@duffymo's answer is the most common solution to this problem, and the one you should probably follow.

However, if you're feeling saucy, and if your situation supports it, then you could consider using Spring's AspectJ support to autowire your non-spring-managed domain objects with spring beans:

[...] contains an annotation-driven aspect that exploits this capability to allow dependency injection of any object. The support is intended to be used for objects created outside of the control of any container. Domain objects often fall into this category because they are often created programmatically using the new operator, or by an ORM tool as a result of a database query.

It's verging on voodoo, this stuff, and it only works on certain appservers, but it might be the tool for you.

like image 195
skaffman Avatar answered Sep 22 '22 09:09

skaffman