简体   繁体   中英

Java scope and life cycle of bean in spring

I have this question, in a spring web application when we declare a bean singleton and inside a bean prototype every time that we invoke a singleton the prototype bean will be same, but if i want a prototype component inside a faacde inside a controller, how last component can be prototype if other are singleton? The schema is this singleton controller->singleton facade->prototype service Thank u.

If I understood you correctly there are many options that you can use. The most popular:

1. Scoped proxy . Add this annotation to you prototype bean:

@Scope( value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)

2. @Lookup annotation with method injection:

@Component
public class SingletonFacade {

   @Lookup
   public PrototypeBean getPrototypeService() {
       return null;
   }
}

3. ObjectFactory Interface :

@Componenet
public class SingletonFacade {

   @Autowired
   private ObjectFactory<PrototypeService> prototypeBeanObjectFactory;

   public PrototypeBean getPrototypeInstance() {
       return prototypeBeanObjectFactory.getObject();
   }
}

You can find more information here - https://www.baeldung.com/spring-inject-prototype-bean-into-singleton

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