这两天用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一发(原理后面补,,最近在研究源码,还没看这一块

@Component
public 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;
}
}

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

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

运行,可以运行,报NPL

打印结果

生产中....
Exception in thread "main" java.lang.NullPointerException
@Component
public 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!

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

原文地址:https://blog.csdn.net/u013076044/article/details/70880718

spring bean-- autowired的正确用法的更多相关文章

  1. Spring注解@Component、@Repository、@Service、@Controller,@Autowired、@Resource用法

    一.Spring定义bean,@Component.@Repository.@Service 和 @Controller Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥 ...

  2. Spring MVC中Session的正确用法<转>

    Spring MVC是个非常优秀的框架,其优秀之处继承自Spring本身依赖注入(Dependency Injection)的强大的模块化和可配置性,其设计处处透露着易用性.可复用性与易集成性.优良的 ...

  3. 【转】Spring MVC中Session的正确用法之我见

    Spring MVC是个非常优秀的框架,其优秀之处继承自Spring本身依赖注入(Dependency Injection)的强大的模块化和可配置性,其设计处处透露着易用性.可复用性与易集成性.优良的 ...

  4. Spring MVC中Session的正确用法之我见

    Spring MVC是个非常优秀的框架,其优秀之处继承自Spring本身依赖注入(Dependency Injection)的强大的模块化和可配置性,其设计处处透露着易用性.可复用性与易集成性.优良的 ...

  5. new出来的对象无法调用@Autowired注入的Spring Bean

    @Autowired注入Spring Bean,则当前类必须也是Spring Bean才能调用它,不能用new xxx()来获得对象,这种方式获得的对象无法调用@Autowired注入的Bean. 1 ...

  6. Spring Bean依赖但注入(autowired或resource)时NullPointerException(xml和annotation混用的场景下)

    项目中同时使用了xml和annotation的方式管理Spring Bean 启动时候报NullPointerException,依赖注入失败! 参考: http://fly0wing.iteye.c ...

  7. spring bean自动注入

    使用 @Repository.@Service.@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的 ...

  8. Spring(3)——装配 Spring Bean 详解

    装配 Bean 的概述 前面已经介绍了 Spring IoC 的理念和设计,这一篇文章将介绍的是如何将自己开发的 Bean 装配到 Spring IoC 容器中. 大部分场景下,我们都会使用 Appl ...

  9. spring注解-@Autowired。@Resource。@Service

    Spring的@Autowired注解.@Resource注解和@Service注解 什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点: ...

  10. spring 中配置sessionFactory及用法

    spring 中配置sessionFactory及用法 方法一: 1.在Spring的applicationContext.xml中配置bean <!-- 启用注解注入  -->      ...

随机推荐

  1. nginx 实现浏览器文件下载服务

    nginx 实现浏览器文件下载服务 2018/07/21 这里记录如何用 nginx 搭建一个简易的 file server,实现在浏览器上进行文件的下载操作. 要实现文件下载功能非常非常容易,不需要 ...

  2. 记录一次 Linux crontab 执行django 脚本 失败 的经历和解决办法

    目的是想通过定时任务来执行一次数据统计,本来可以用celery来做,但是想着这个项目整个就没用到异步的地方,所以决定用crontab来做.之前做过数据库的热备份,想来用该没啥问题,但是现实打脸啪啪响. ...

  3. 关于Extjs获取容器和元素的方法

    1.当前对象的父对象(上级对象) this.ownerCt: 2.当前对象的下一个相邻的对象 this.nextSibling(); 3.当前对象的上一个相邻的对象 this.previousSibl ...

  4. 利用xcode Build生成模拟器运行包

    真机只能运行.ipa包 模拟器上只能运行.app包 xcode中生成.app包步骤: 启动xcode IDE,打开gigold源码工程 [project]——[gigold]——[Basic]:修改V ...

  5. threading包的例子和queue包的例子

    参考:https://www.cnblogs.com/tkqasn/p/5700281.html 参考:https://www.cnblogs.com/tkqasn/p/5700281.html th ...

  6. springboot logback 配置 通配符不行就这样

    <?xml version="1.0" encoding="UTF-8"?><configuration> <property n ...

  7. B/S选择文件夹上传

    1 背景 用户本地有一份txt或者csv文件,无论是从业务数据库导出.还是其他途径获取,当需要使用蚂蚁的大数据分析工具进行数据加工.挖掘和共创应用的时候,首先要将本地文件上传至ODPS,普通的小文件通 ...

  8. 实现网页qq在线咨询功能

    在自己的网页中实现qq在线咨询,给图片或链接添加地址为:tencent://message/?uin=你的qq号码!就可以了. <a href="tencent://message/? ...

  9. 选项卡jq

    1.无定时器 $(function(){$('.banner-point li').on('click',function(){$(this).addClass('active').siblings( ...

  10. UVA10870 Recurrences (矩阵快速幂及构造方法详解)

    题意: F(n) =  a1 * F(n-1) + a2 * F(n-2)+ ···· + ad * F(n-d). 求给你的n . 很明显这是一道矩阵快速幂的题目. 题解: [Fn-1, Fn-2, ...