1
votes

I am using Spring boot. I have some question regarding the spring boot beans.

But I have doubt

I use bean which are default scope that is singleton. So they will have only one instance per application.

@Configuration
public class ...{

     @Bean
     public void method() {}
}

And

Now i use bean which scope is prototype. So they will have each instance per request.

@Configuration
public class ...{

     @Bean 
     @Scope("prototype")
     public void method() {}
}

But

I want single instance per user..? all request use single instance per user.

2
prototype scoped isn't per request!. Define instance per user? Is session scoped enough if it is something else you will need to implement your own scope. - M. Deinum
@M.Deinum but when use prototype scope they work like per request. - Kailas Biradar
No they don't. Each method invocation will lead to a new instance of the bean (so if you invoke 2 methods on the bean you will get 2 instances instead of 1). At least when properly used as a scoped proxy!. - M. Deinum
@KailasBiradar prototype!=request scope. Prototype will give you new bean everytime it is requested - and this can happen multiple times on single request. - Antoniossss
@Antoniossss ok - Kailas Biradar

2 Answers

2
votes
@Configuration
class Abc {
 @Bean
 @Scope("session")
 public YourBean getYourBean() {
 return new YourBean();
}
}
0
votes

You will need to define one singleton bean with a property using prototype bean:(xml example)

enter image description here

With @bean definition:

@Component
@Scope("singleton")
public class SingletonBean {

   // ..

     @Autowired
     private PrototypeBean prototypeBean;
   //..

}



@Component
@Scope("prototype")
public class PrototypeBean {
 //.......
}

Example: https://www.baeldung.com/spring-inject-prototype-bean-into-singleton