Home > Software design >  How to create a non reusable bean on springboot
How to create a non reusable bean on springboot

Time:11-24

By default, on springboot, when we declare a method with @Bean, the object instance will be shared across all objects that request for @Autowired that class...

What if I want spring to deliver different instances for each autowire class that request that object?

I mean instead of share one single instance of a bean have multiple "disposable" beans for each requisition of that object?

Why I want that?

the reason is quite simple, RestTemplateBuilder is a common bean used in most spring application, by its nature this builder is STATEFUL which means that any changes made to one class to its structure will cause side effects to all other objects that use it.

CodePudding user response:

If you want to have a different instance for each class you inject you should use the scope annotation as follow:

@Bean
@Scope("prototype")
public Person personPrototype() {
    return new Person();
}

you can also use the constant as follow:

@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  • Related