Inject does not work with the new operator

Can someone explain why the @Inject is null when its class is initialized with the new operator?

 public class A{ @Inject B b; ... ... } 

When the specified class is created as A a = new A(); I get b as null . Can anyone explain why? I know this works when I implement class A. But I want to know why it does not work with the new operator. What does spring do?

+4
source share
6 answers

Dependency injection is handled by the spring container, so only objects created by the container will be exposed to it.

In this case, you create the object manually using the new operator, the spring container will not know about the creation of the object.

A possible solution is to use @Configurable Annotation (and AspectJ) to solve this problem, as stated in the documentation

Also see this answer

+6
source

Spring does not have the ability to automatically install dependencies in beans so that it does not create itself. Dependency injection must be handled by the Spring container. If you use new to create objects, you are not using the Spring container at all. Instead of creating an instance, you should request a container for the objects. Thus, the container will be bound to the life cycle of this object.

 A a = new A(); 

So your object referenced by a is not managed by Spring. Therefore, it will not be able to insert any dependent objects into a .

You should get an instance of a from the container, something like this:

 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); A a = context.getBean("myBean"); 

PS: - Although out of context, but this to-new-or-not-to-new blog is a pleasant read.

+4
source

How should an injector notice and act on new ? This is a language operation that cannot be intercepted.

0
source

B will be introduced in the Bean created by spring.

 A a = new A(); 

it is not spring created, it is not spring bean.

In your .xml context, you need to create a Type A Bean and use it.

0
source

Despite the fact that this is so, the injection is not so magical. If you create an instance with the β€œnew”, all that happens is that the constructor is called and the code in the constructor is processed.

How to get an instance of a class with the entered values ​​depends on the technology you are using.

0
source

static access to the entity manager in spring and unusual architecture (Can someone move this link to the last paragraph, please. It is impossible to go through it in the right place with my phone)

Add @Configurable to the class. Then spring will be injected into this class, even if it is created with a normal new one.

But this requires a real AspectJ.

See this question and answer (link at the beginning) for details.

0
source

Source: https://habr.com/ru/post/1486757/


All Articles