当前位置: 代码迷 >> 综合 >> Springboot @Lazy(单实例的懒加载)
  详细解决方案

Springboot @Lazy(单实例的懒加载)

热度:96   发布时间:2023-09-30 04:19:58.0

首先我们要了解到什么是懒加载。懒加载是一种思想也是一种设计模式,当需要使用时才创建或实例化资源。个人猜想Springboot中的懒加载应该是由反射的动态编程实现的。

@Lazy用于单实例的懒加载。容器初始化前单实例不会被创建,只有当从容器中调用实例时,实例才被创建。

import com.michael.annotation.demo.POJO.Person;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.*;@Configuration
@ComponentScan(value = {
    "com.michael"},
excludeFilters = {
    @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {
    SpringBootApplication.class})
})
public class MyConfig {
    //注意,@Lazy注解用于单实例Bean@Lazy@Bean@Scope(value = "singleton")public Person person(){
    System.out.println("get");return new Person("Steven", 11);}
}
import com.michael.annotation.demo.POJO.Person;
import com.michael.annotation.demo.configuration.MyConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);out.println("Container has been initialised.");ApplicationContext applicationContext  =  new AnnotationConfigApplicationContext(MyConfig.class);Person person1 = (Person) applicationContext.getBean("person");for(String name : applicationContext.getBeanDefinitionNames()){
    out.println(name);}}}

输出:

get
2020-03-20 10:08:58.945  INFO 10297 --- [           main] c.m.annotation.demo.DemoApplication      : Started DemoApplication in 0.53 seconds (JVM running for 0.859)
Container has been initialised.
get
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
personService
person

实验输出结果和预期不符。我们可以看到,实例在容器创建前就创建了。