spring 懒加载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shen19920619/article/details/78139548

spring 组件的来加载需要借助注解@Lazy 并且在service 中采用BeanFactory 容器中去获取到对应的bean , 而不是直接注入

例如

@autowire

private TestLazyComponent    //这种做法是错误的



直接看代码

@Lazy
@Component
public class TestLazyComponent {


static {

System.err.println("init TestLazyComponent");
}

public void say() {
System.out.println("hello world");
}
}



@SpringBootApplication
public class TestApplication implements CommandLineRunner {


public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}


@Autowired
BeanFactory beanFactory;


public void dosometh() {
TestLazyComponent bean = beanFactory.getBean(TestLazyComponent.class);
bean.say();
}



@Override
public void run(String... arg0) throws Exception {
dosometh();
}
}

猜你喜欢

转载自blog.csdn.net/shen19920619/article/details/78139548
今日推荐