ProxyMode: Prototype Dependency of a Singleton Bean


 

Default scope is singleton, what to do prototype?

@Component
@Scope("prototype")
public class Dependency {

What if a bean use this component as a dependency and we want this dependency prototype for every single instance of the bean?


Bean:
@Component
public class Service_Impl implements Service {

@Autowired
public Dependency dependency;

@Override
public void print() {
System.out.println(dependency);
}
}

Application contex
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@Autowired
public Service service1;
@Autowired
public Service service2;

@Override
public void run(String... args) throws Exception {
service1.print();
service2.print();
}
}

Even if the dependency scope set as prototype, output will be:

com.example.demo.Dependency@43e9e0b1
com.example.demo.Dependency@43e9e0b1

which means same hash code and dependency is still singleton.


If we define proxyMode in @Scope annotation, it will work:

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Dependency {

 

and output will be:

com.example.demo.Dependency@3eab8a9d
com.example.demo.Dependency@544b6c7c

Comments