Lazy
Under normal circumstances, bean loading starts after the container is started, so if there is an error in the loading process, it can be found immediately. Due to some specific business requirements, some beans need to be created at the first request of the IoC container. These beans can be marked as delayed loading.
XML
In the XML configuration file, it is controlled by the lazy init attribute of the bean tag. If multiple beans are controlled to be lazy loaded, the bean can be placed under the beans tag and controlled by the default lazy init = "true" of the beans tag.
xml configuration:
<?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 and Two
public class One { public One(){ System.out.println("one init"); } } public class Two { public Two(){ System.out.println("two init"); } }
Test code:
@Test public void test() { ApplicationContext app = new ClassPathXmlApplicationContext("di7.xml"); System.out.println("Loading completed"); app.getBean("one"); }
The operation results are as follows:
Before loading, only two init is printed, and one init is printed after getBean("one") is called. It can be seen that it is loaded after calling.
annotation
In the annotations, it is controlled by @Lazy.
MyConfig
@Configuration public class MyConfig { @Bean() @Lazy public One one(){ return new One(); } @Bean() public Two two(){ return new Two(); } }
Test code
@Test public void test() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); System.out.println("Loading completed"); app.getBean("one"); }
The operation results are as follows: