2
@Component
@Qualifier("impl1")
public class Implementation1 implements BaseInterface{  
    @Override
    public String process() {
        return "Implementation1";
    }

}

@RestController
public class HomeController {
    
    @GetMapping("/impl1")
    @Autowired
    public String impl1(@Qualifier("impl1")Implementation1 impl) {
        return impl.process()+" "+impl.hashCode();
    }
}

By default all the beans are supposed be of singleton scope in spring boot application, and so I suppose their hashCode should be same as well. But that is not the case for me. Please let me know if I am missing something here.

Above are the Controller and Bean class, BaseInterface is a simple interface with process() abstract method. Yet for each Request I am getting a different hashCode. Had it been treated as a singleton the hashCOde should have been same for each request.

I expect there to be same hash code each time

1 Answers1

0

This is syntactic sugar for

public String impl1(@RequestParam @Qualifier("impl1")Implementation1 impl) 

If you take a look at the definition of @RequestParam you should see the actual scope of the parameter (which should be Session).

Changing that scope would be a difficult proposition since you would have ro handle concurrent requests using the same object.

s_qw23
  • 354
  • 2
  • 11
  • but I do not want to take it from http request I want it from Spring, basically this to test if spring provides same object by default or not(to prove weather or not the scope of beans by default is singleton) – Piyush Lovanshi Aug 15 '23 at 01:02
  • 1
    Then you have to inject it. Just add private Implementation impl; at the top of the controller class. That will give you a singleton bean and an accurate representation of stamdard behaviour. – s_qw23 Aug 15 '23 at 04:56