You can also use the injection method . As a rule, you need to get a new instance of a singleton bean from the context, but it can also be used in your case.
Example:
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>
Thus, a lazy bean will be initialized only once upon request.
szhem source share