shai.tap
shai.tap

Reputation: 129

How to get object with new that has @Autowired?

I am using the Spring mvc 3.1 framework and I have factory class the give "new Object()"

and the Object as @Autowired inside which return null.

All the beans are in servlet-context.xml

How can O perform new and still use the @Autowired in the Object?

Thanks.

Upvotes: 1

Views: 541

Answers (1)

Scott Frederick
Scott Frederick

Reputation: 5115

If you want to @Autowire a bean of type A into a bean of type B, Spring must manage the lifecycle of both beans. If you manually create bean A using "new()", Spring has now way to manage that bean instance and hence no way to auto-wire it.

If the instantiation of bean A is complex, you can use a Spring factory bean to manage it. There is a good explanation of factory beans here: http://blog.springsource.org/2011/08/09/whats-a-factorybean/

Upvotes: 2

Related Questions