Bạn cũng có thể sử dụng method injection. Như một quy luật, nó được yêu cầu để có được một trường hợp mới của một hạt đơn từ một bối cảnh, nhưng nó có thể được sử dụng trong trường hợp của bạn quá.
mẫu:
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>
Vì vậy, bạn lười biếng đậu sẽ được khởi tạo chỉ một lần theo yêu cầu.
có thể trùng lặp của [Có nhà máy sản xuất proxy lười xuân vào mùa xuân không?] (Http://stackoverflow.com/questions/2391168/is-there-a-spring-lazy-proxy-factory-in-spring) – skaffman
những gì về việc đi qua một nhà máy ServiceB vào ServiceA? –