这两天用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. 基于Xilinx Kintex-7 FPGA K7 XC7K325T PCIeX8 四路光纤卡

    基于Xilinx Kintex-7 FPGA K7 XC7K325T PCIeX8 四路光纤卡 1. 板卡概述   板卡主芯片采用Xilinx公司的XC7K325T-2FFG900 FPGA,pin_ ...

  2. 一、.Net Core 分块上传文件

    一..Net Core 分块上传文件 一.前端实现 @* For more information on enabling MVC for empty projects, visit http://g ...

  3. 第一次写的MySQLHelper

    一. 第一次写MysqlHelper,用来管理城市的数据库 二.MySQLHelper源代码 using MySql.Data.MySqlClient; using System; using Sys ...

  4. less:注释

    less有两种注释方法,一种是// 一种是/**/ 这两者的区别是/**/是会被编译成css里面,而//则不会 举个例子(使用的less在线编译器) 我们看到//注释并没有编译到css里面

  5. 有关shell中冒号的特殊用法

    有关shell中冒号的特殊用法,供朋友们参考. : ${VAR:=DEFAULT} 当变量VAR没有声明或者为NULL时,将VAR设置为默认值DEFAULT.如果不在前面加上:命令,那么就会把${VA ...

  6. 机器学习:2.NPL自然语言处理

    1. 词带的简单解释: 每一个词出现了多少次,缺点是不知道顺序 2.seq2seq自然语言处理的核心 RNN: 一对一:输入一个,输出一个 一对多:输入一个,输出多个 多对一:输入多个,输出一个 多对 ...

  7. RestTemplate 发送post请求

    springboot使用restTemplate post提交值 restTemplate post值 post提交有 FormData和Payload 两种形式: 第一种是formdata形式,在h ...

  8. 修改Win7登陆界面墙纸

    修改Win7登陆界面墙纸 修改注册表.reg Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\W ...

  9. Python---基础---dict和set

    2019-05-20 ------------------------------ 写一个程序来管理用于登陆系统的用户信息:登录名字和密码,登录用户账号建立后,已存在用户可以用登陆名字和密码重返系统, ...

  10. linux运维、架构之路-Nginx提高

    一.虚拟主机搭建 1.基于域名的虚拟主机 [root@web01 html]# cat nginx.conf worker_processes ; events { worker_connection ...