In the following example, how would I have myMainService and barService, which are themselves both prototype scoped, to refer to the same instance of fooService? (I've kept these beans stateless to keep the example small, just assume that they all have state)
Code:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="myMainService" class="com.example.spring.MyMainService" autowire="constructor" scope="prototype"/> <bean id="fooService" class="com.example.spring.FooService" scope="prototype"/> <bean id="barService" class="com.example.spring.BarService" autowire="constructor" scope="prototype"/> </beans>Code:public class Main { public static void main(String[] args) { GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext("classpath:/applicationContext.xml"); applicationContext.getBean(MyMainService.class).sayHello(); } } class MyMainService { private final FooService foo; private final BarService bar; public MyMainService(FooService foo, BarService bar) { this.foo = foo; this.bar = bar; } public void sayHello() { // how do I have MyMainService and BarService // to refer to the same instance of FooService? System.out.println(foo); bar.print(); } } class FooService {} class BarService { private final FooService foo; public BarService(FooService foo) { this.foo = foo; } public void print() { System.out.println("Bar has " + foo); } }


Reply With Quote
