spring注解的懒加载 @Lazy

@Lazy注解的概念

         用于标识bean是否需要延迟加载   

即ioc容器启动的时候 是否会直接加载这个bean  如果添加了@Lazy 则容器启动的时候不创建对象,仅当第一次使用(获取)bean的时候才创建被初始化      

源码如下

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {

	/**
	 * Whether lazy initialization should occur.
	 */
	boolean value() default true;

}

   通过源码和官方文档可知    @lazy的作用范围 可以在    @Component  @Bean  @Configuration 上

   @Lazy 的value 为 Boolean  为 true 开启懒加载 为 Flase 关闭      默认为 true

官方注释如下!

如果@Component或@Bean定义中不存在此注解(@Lazy),则会直接初始化。如果存在并设置为true,则@Bean或@Component将不会被初始化,直到被另一个bean引用或从封闭的BeanFactory中显式获取。如果存在并设置为false,则bean将在启动时由bean工厂实例化,这些工厂执行单例的初始化。

如果@Configuration类中存在Lazy,则表明该@Configuration中的所有@Bean方法都应该被懒惰地初始化。如果在@Lazy-annotated @Configuration类中的@Bean方法上存在@Lazy且为false,则表明存在“默认延迟”行为,并且应该热切地初始化bean。

此外 @Lazy 还可以放到 @Autowire  和  @Inject 上  (这个一般不用)

实例   放在 @Bean 上 

   

package com.lqp.test.day01;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
//配置类
@Configuration
public class ConfigurationTest {

	@Bean
	@Lazy
	public User user() {
		System.out.println("我是懒加载");
		return new User("11", "lqp");
	}


}

  测试 

package com.lqp.test.day01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest1 {

	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationTest.class);
		
		System.out.println("ioc容器启动");
		User user =(User) context.getBean("user");
	    System.out.println(user);
	}
}
ioc容器启动
我是懒加载
User [age=11, name=lqp]

 

         

@Lazy注解的作用主要是减少springIOC容器启动的加载时间

发布了19 篇原创文章 · 获赞 8 · 访问量 4135

猜你喜欢

转载自blog.csdn.net/paohui001lqp/article/details/97111701