您也可以使用method injection。 通常需要從上下文中獲取單例bean的新實例,但它也可以用於您的情況。
樣品:
package org.test.lazy;
public abstract class ParentBean {
public abstract LazyBean getLazy();
public void lazyDoingSomething() {
getLazy().doSomething();
}
}
package org.test.lazy;
public class LazyBean {
public void init() {
System.out.println("Initialized");
}
public void doSomething() {
System.out.println("Doing something");
}
}
package org.test.lazy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class LazyTest {
@Autowired
private ParentBean parentBean;
@Test
public void test() {
parentBean.lazyDoingSomething();
parentBean.lazyDoingSomething();
}
}
<?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
">
<import resource="classpath:org/test/lazy/Lazy-context.xml"/>
<bean id="parentBean" class="org.test.lazy.ParentBean">
<lookup-method bean="lazyBean" name="getLazy"/>
</bean>
</beans>
<?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
"
default-lazy-init="true">
<bean id="lazyBean" class="org.test.lazy.LazyBean" init-method="init" />
</beans>
所以你懶惰的bean只會根據需求初始化一次。
可能重複的[春天有沒有一個春天的懶惰代理工廠?](http://stackoverflow.com/questions/2391168/is-there-a-spring-lazy-proxy-factory-in-spring) – skaffman
將ServiceB工廠傳遞給ServiceA怎麼樣? –