首页 > 编程语言 > 详细

Spring - 实例化与延迟实例化

时间:2021-08-09 14:01:18      阅读:26      评论:0      收藏:0      [点我收藏+]

前言

上一章谈论了模式注解声明组件(Bean)的应用,这里记录下Spring实例化的一些细节。


实例化

  • 通常我们通过@Component和@Autowired声明、使用Bean
public class TestController {
    @Autowired
    private TestInter testInter;
}
public interface TestInter {
    void sayHello();
}
@Component
public class TestOne implements TestInter {
    public TestOne () {
        System.out.println("TestOne init");
    }

    @Override
    public void sayHello() {
        System.out.println("Hello TestOne");
    }
}
  • 可以看出,默认机制下,应用程序启动时IOC容器就开始实例化对象。

技术分享图片


忽略当前要注入的bean

  • 当我们注入一个并没有实例化的对象。
//@Component
public class TestOne implements TestInter {
    public TestOne () {
        System.out.println("TestOne init");
    }
}
public class TestController {
    @Autowired
    private TestInter testInter;
}
  • 此时程序抛出异常

技术分享图片

  • @Autowired(required = false) 忽略当前要注入的bean
public class TestController {
    @Autowired(required = false)
    private TestInter testInter;
}
  • 可看出,程序正常启动

技术分享图片


@Lazy 延迟实例化

  • 通过@Lazy注解让Bean延迟实例化
public class TestController {
    @Autowired
    @Lazy
    private TestInter testInter;

    @GetMapping(value = "/test")
    public void test(){
        testInter.sayHello();
    }
}
@Component
@Lazy
public class TestOne implements TestInter {
    public TestOne () {
        System.out.println("TestOne init");
    }

    @Override
    public void sayHello() {
        System.out.println("Hello TestOne");
    }
}

技术分享图片

- End -
梦想是咸鱼
关注一下吧
技术分享图片

Spring - 实例化与延迟实例化

原文:https://www.cnblogs.com/maggieq8324/p/15118088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!