spring bean-- autowired的正确用法

来源:互联网 发布:身份证复印件软件v3.4 编辑:程序博客网 时间:2024/05/18 01:18

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

 @Autowired  Worker worker;

都会报黄,用过这个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  }}

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

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

因为在register里面会进行判断

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

后来无奈搜索引擎一发

发现了可以 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;    }}

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

@Componentpublic class Factory {    @Autowired Worker worker;    public void createProduct(){        System.out.println("生产中....");        worker.doWork();        System.out.println("生产完成...");    }}

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

生产中....Exception in thread "main" java.lang.NullPointerException
@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("生产完成...");    }}

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

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!

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

0 0
原创粉丝点击