3

Like in subject. I didn't see any difference between those approaches. Prototype bean is clear when I use only those. But in spring we base on the singleton's beans so when I use bean with scope prototype in singleton bean it look the same like I want to create new Object.

    @Service
    public class SomeService{
        @Autowired
        private ApplicationContext applicationContext;

    public void someClass() {
       PrototypeObject prototypeObject = applicationContext.getBean(PrototypeObject .class);
       PrototypeObject prototypeObject = new PrototypeObject();
    }
   }

Is there a difference between those two approaches?


The best answer for me is: I lost any advantages of IoC.

Adriano
  • 874
  • 2
  • 11
  • 37
  • 1
    The difference is when you create an object manually, you lose all IoC features on it (i.e. must manually inject dependencies, configuration values, call listeners, perform transaction demarkation etc etc - all stuff that container does automatically for beans) – Alex Salauyou Nov 16 '18 at 07:22
  • Refer to this - https://stackoverflow.com/questions/16058365/what-is-difference-between-singleton-and-prototype-bean – Anish B. Nov 16 '18 at 07:26

2 Answers2

1

They are completely different.

Spring Managed Beans : Whenever you create a bean with @Bean or invoke any bean with @Inject/@Autowired they are in Spring context and they can do Spring related functionality or Alternatively get it from application Context( Although it is not recommended because it is against the Inversion of control).

Non Spring Managed Beans : Whenever you create a bean with new, they are moved out of spring context and they can't be used anymore in Spring Managed Context.

Objects created with new are not aware of any Spring annotations and related functionality.

Mohit Sharma
  • 340
  • 2
  • 11
1

Lets starts with 'Singleton' which everyone knows

In spring by default all beans are singleton, which mean only one copy is existed with multiple references

Second 'Prototype' which is interesting

Prototype scope will return a difference instance everytime it is requested from the container, so in spring if you make any bean as prototype everytime you will get different instance with autowired propertied of that bean

Third with 'new' keyword

This will return new object, properties with default values or null and also this is object which is not registered in spring Application context

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98