正常狀況下,bean的加載是容器啓動後就開始的,這樣若是加載的過程當中有錯誤,能夠立馬發現。因爲一些特定的業務需求,須要某些bean在IoC容器在第一次請求時才建立,能夠把這些bean標記爲延時加載。spring
在XML配置文件中,是經過bean
標籤的lazy-init
屬性來控制的,若是控制多個bean都是懶加載,那麼能夠把bean放入beans
標籤下面,經過beans
標籤的default-lazy-init="true"
來控制。
xml配置:app
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="one" class="com.learn.di.One" lazy-init="true"/> <bean id="two" class="com.learn.di.Two"/> </beans>
One和Two測試
public class One { public One(){ System.out.println("one init"); } } public class Two { public Two(){ System.out.println("two init"); } }
測試代碼:spa
@Test public void test() { ApplicationContext app = new ClassPathXmlApplicationContext("di7.xml"); System.out.println("加載完畢"); app.getBean("one"); }
運行結果以下:
加載完畢以前,只打印了two init,調用getBean("one")後,纔打印出one init,能夠看出,是在調用後才加載。code
在註解中,是經過@Lazy來控制的。
MyConfigxml
@Configuration public class MyConfig { @Bean() @Lazy public One one(){ return new One(); } @Bean() public Two two(){ return new Two(); } }
測試代碼blog
@Test public void test() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); System.out.println("加載完畢"); app.getBean("one"); }
運行結果以下:get