Home > Net >  What will happen if I tried to instantiate spring bean manually
What will happen if I tried to instantiate spring bean manually

Time:11-03

Reading some source code and I stumbled upon this spring bean

@Service
public class ValidationService {...}

Which is instantiated manually using the new() operator in many places

ex: var validationService=new ValidationService();

Now I am thinking to refactor all of these instantiations and replace it with proper spring injection.

It made me think about what would happen if we instantiated a bean using the new() operator. Will it create a new instance of the bean or will it just retrieve the spring managed instance ?

CodePudding user response:

When the object is instantiated manually, it acts like a normal Java object.

Spring is not involved, so all the "spring features" (Inversion of control, dependency injection, etc..) not available.

  • Related