Please take a look at code below:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
@Slf4j
class BeanScopeTestController {
private final SingletonBean singletonBean1;
@Autowired
BeanScopeTestController(SingletonBean singletonBean) {
this.singletonBean1 = singletonBean;
}
@GetMapping
String checkTheSameInstance(@Autowired SingletonBean singletonBean2) {
log.info(singletonBean1.toString());
log.info(singletonBean2.toString());
boolean methodEquals = singletonBean1.equals(singletonBean2);
boolean instanceEquals = singletonBean1 == singletonBean2;
return String.format("method equals: %s; instance equals: %s", methodEquals, instanceEquals);
}
}
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ToString
@EqualsAndHashCode
class SingletonBean {
private static int idProvider = 0;
private final int id;
public SingletonBean() {
this.id = idProvider++;
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
}
How it is possible that the output of GET
/test
endpoint (method BeanScopeTestController#checkTheSameInstance
) is method equals: false; instance equals: false
?
Default scope for spring @Bean is Singleton
to I would expect that class field singletonBean1
and method parameter singletonBean2
would get the same instance from Spring container, but those references are autowired with different instances of SingletonBean
. Does @Autowire
on method parameter in Spring MVC work differently so maybe bean scope is somehow overriden then? Or the reason of that is different?
I expected to have the same instance of SingletonBean
autowired by class field and method parameter.