为了完整起见,我发布了 XML 配置方式。
SSCCE
package Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main extends HttpServlet {
static class A
{
private B b;
public void setB(B b)
{
this.b = b;
}
public B getB() {
return b;
}
}
static class B {}
static class C
{
private static B b = new B();
public static B getB()
{
return b;
}
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
A a = (A) context.getBean(A.class);
System.out.println(a.getB() == C.getB());
}
}
上下文
<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.xsd">
<bean class="Test.Main.A">
<property name="B">
<bean class="Test.Main.C" factory-method="getB"></bean>
</property>
</bean>
</beans>
印刷
true