spring bean-- autowired的正确用法

本文探讨了Spring框架中依赖注入的最佳实践,强调了构造方法注入的重要性,并通过实例展示了如何使用断言来确保依赖项非空,从而在容器启动时就能发现潜在错误。
                       

这两天用idea写spring注入的时候每一次

 @Autowired  Worker worker;
  
  • 1
  • 2

都会报黄,用过这个ide的都知道,说明你代码需要重构了。
然后提示的信息是

 

Spring Team recommends: “Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies”

大致意思是 ,每一次的依赖注入都用构造方法吧,并且每一次对强制依赖关系使用断言,大白话就是我们这样可以在构造方法里面做点校验了,这样在spring容器启动的时候就会发现错误。就类似于编译器那些在编译器就可以发现的错误,这样防止在使用的时候出现运行时异常。导致程序崩掉。强制依赖关系可以理解为,B的方法中调用A的方法

群里面还发了个例子

// Fieldinjection/NullPointerException example:  class MyComponent {  @Inject MyCollaborator collaborator;  public void myBusinessMethod() {    collaborator.doSomething(); // -> NullPointerException  }}  Constructor injection should be used:  class MyComponent {  private final MyCollaborator collaborator;  @Inject  public MyComponent(MyCollaborator collaborator) {    Assert.notNull(collaborator, "MyCollaborator must not be null!");    this.collaborator = collaborator;  }  public void myBusinessMethod() {    collaborator.doSomething(); // -> safe  }}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

本来实现一个null的bean很简单

显示用BeanFactoryPostProcessor实现,发现如果添加一个null会直接报错

因为在register里面会进行判断

Assert.hasText(beanName, "Bean name must not be empty");Assert.notNull(beanDefinition, "BeanDefinition must not be null");
  
  • 1
  • 2

后来无奈搜索引擎一发

发现了可以 factorybean一发(原理后面补,,最近在研究源码,还没看这一块

@Componentpublic class Worker implements FactoryBean<Void> {    public void doWork(){        System.out.println("do Work...");    }    @Override    public Void getObject() throws Exception {        return null;    }    @Override    public Class<?> getObjectType() {        return Worker.class;    }    @Override    public boolean isSingleton() {        return true;    }}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

那么我的依赖注入先这么写

@Componentpublic class Factory {    @Autowired Worker worker;    public void createProduct(){        System.out.println("生产中....");        worker.doWork();        System.out.println("生产完成...");    }}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

运行,可以运行,报NPL
打印结果

生产中....Exception in thread "main" java.lang.NullPointerException
  
  • 1
  • 2
@Componentpublic class Factory {    final Worker worker;    @Autowired    public Factory(Worker worker) {        Assert.notNull(worker, "worker must not be null!");        this.worker = worker;    }    public void createProduct(){        System.out.println("生产中....");        worker.doWork();        System.out.println("生产完成...");    }}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

结果 无法运行,容器启动失败

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factory' defined in file [F:\code\github\2017-up\spring-code\target\classes\com\wuhulala\studySpring\testnull\Factory.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.wuhulala.studySpring.testnull.Factory]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: worker must not be null!
  
  • 1
  • 2

善用断言,在程序中启动的时候就发现错误。

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.youkuaiyun.com/jiangjunshow

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值