简体   繁体   中英

What is the difference between bean with scope prototype and new Object in singleton bean?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM