Spring中的奇怪行为

时间:2014-01-07 09:19:06

标签: spring

我正在使用Spring的SmartFactoryBean接口来创建一个对象。此接口有一个方法isEagerInit(),根据文档说明何时初始化从此接口的getObject()方法返回的对象。此接口isPrototype()中还有另一种方法,它告诉spring容器中对象的范围。

现在,我注意到的奇怪行为是使用isEagerInit()方法。如果我从此方法返回true,我可以看到我的对象的两个实例正在创建,这与isPrototype()方法相矛盾。

示例类:

public class MyBean {
    public MyBean() {
        System.out.println("MyBean Instance created...");
    }

    public void doSomething() {
        System.out.println("I am doing something...");
    }
}

public class MyBeanSmartFactoryBean implements SmartFactoryBean<MyBean> {
    @Override
    public boolean isPrototype() {
        return false;
    }

    @Override
    public boolean isEagerInit() {
        return false;
    }

    @Override
    public MyBean getObject() throws Exception {
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

@Component("sample")
public class Sample {
    @Autowired
    @Qualifier("myBeanSmartFactoryBean")
    private MyBean myBean;

    public void doSample() {
        System.out.println("Inside Sample; calling MyBean to doSomething...");
        myBean.doSomething();
    }
}

Spring config:

<bean id="myBeanSmartFactoryBean" class="com.demo.MyBeanSmartFactoryBean" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:annotation-config />
<context:component-scan base-package="com.demo" />

测试代码

public class Test {
    public static void main(String[] args) {
        final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");

        final Sample sampleOne = (Sample) applicationContext.getBean("sample");
        sampleOne.doSample();

        System.out.println("++++++++++++++++++++++");
        final Sample sampleTwo = (Sample) applicationContext.getBean("sample");
        sampleTwo.doSample();

        System.out.println("++++++++++++++++++++++");
        final Sample sampleThree = (Sample) applicationContext.getBean("sample");
        sampleThree.doSample();
    }
}

输出 - 1(当isEagerInit()返回false时)

MyBean Instance created...
Inside Sample; calling MyBean to doSomething...
I am doing something...
++++++++++++++++++++++
Inside Sample; calling MyBean to doSomething...
I am doing something...
++++++++++++++++++++++
Inside Sample; calling MyBean to doSomething...
I am doing something...

输出 - 1(当isEagerInit()返回true时)

MyBean Instance created...
MyBean Instance created...
Inside Sample; calling MyBean to doSomething...
I am doing something...
++++++++++++++++++++++
Inside Sample; calling MyBean to doSomething...
I am doing something...
++++++++++++++++++++++
Inside Sample; calling MyBean to doSomething...
I am doing something...

请注意语句 MyBean Instance created ... 出现两次。

感谢有人能解释发生了什么。

谢谢,

NIRANJAN

0 个答案:

没有答案