TestController.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = \"/test\", method
all the answers above are correct. Controller by default is singleton
and the injected testClass
is instantiated once, because default scoped proxy mode is DEFAULT
from spring doc.
public abstract ScopedProxyMode proxyMode Specifies whether a component should be configured as a scoped proxy and if so, whether the proxy should be interface-based or subclass-based. Defaults to ScopedProxyMode.DEFAULT, which typically indicates that no scoped proxy should be created unless a different default has been configured at the component-scan instruction level.
Analogous to support in Spring XML.
See Also: ScopedProxyMode Default: org.springframework.context.annotation.ScopedProxyMode.DEFAULT
if you want new instance to be injected every time you need, you should change your TestClass
to :
@Component
@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class TestClass {
public TestClass() {
System.out.println("new test class constructed.");
}
public void doSomething() {
}
}
with this additional configuration the injected testClass
will not be really a TestClass
bean but proxy to TestClass
bean and this proxy will understand the prototype
scope and will return new instance every time is needed.