@Autowired的使用:推荐对构造函数进行注释
来源:互联网 发布:resellerclub域名 编辑:程序博客网 时间:2024/06/05 19:46
Spring Team recommends "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".
翻译:
Spring建议”总是在您的bean中使用构造函数建立依赖注入。总是使用断言强制依赖”。
这段代码警告原来的写法是:
@Autowired
private EnterpriseDbService service;
建议后写成下面的样子:
private final EnterpriseDbService service;
@Autowired
public EnterpriseDbController(EnterpriseDbService service) {
this.service = service;
}
奇怪,为何会有这样的建议。
我们知道:@Autowired 可以对成员变量、方法以及构造函数进行注释。那么对成员变量和构造函数进行注释又有什么区别呢?
@Autowired注入bean,相当于在配置文件中配置bean,并且使用setter注入。而对构造函数进行注释,就相当于是使用构造函数进行依赖注入了吧。莫非是这两种注入方法的不同。
以下是:@Autowired和构造方法执行的顺序解析
先看一段代码,下面的代码能运行成功吗?
1 @Autowired2 private User user;3 private String school;4 5 public UserAccountServiceImpl(){6 this.school = user.getSchool();7 }
答案是不能。
因为Java类会先执行构造方法,然后再给注解了@Autowired 的user注入值,所以在执行构造方法的时候,就会报错。
报错信息可能会像下面:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name '...' defined in file [....class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [...]: Constructor threw exception; nested exception is java.lang.NullPointerException
报错信息说:创建Bean时出错,出错原因是实例化bean失败,因为bean时构造方法出错,在构造方法里抛出了空指针异常。
解决办法是,使用构造器注入,如下:
1 private User user;2 private String school;3 4 @Autowired5 public UserAccountServiceImpl(User user){6 this.user = user;7 this.school = user.getSchool();8 }
可以看出,使用构造器注入的方法,可以明确成员变量的加载顺序。
PS:Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造方法–>@Autowired
转载来源:http://blog.csdn.net/ruangong1203/article/details/50992147
- @Autowired的使用:推荐对构造函数进行注释
- @Autowired的使用:推荐对构造函数进行注释
- @Autowired的使用:推荐对构造函数进行注释
- SpringMVC注解@Autowired和@Qualifier 自动注入[根据类型注入] @Autowired 可以对成员变量、方法以及构造函数进行注释, @Qualifier 的
- Spring @Autowired和构造函数的顺序
- 构造函数对数据成员进行初始化的方法
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- 使用Spring2.5的Autowired实现注释型的IOC
- Android自定义View数字圆环(二)
- IntelliJ IDEA修改web项目访问路径
- Android Studio 使用本地gradle配置详解
- Linux下搭建nginx
- javascript 快速获取图片实际大小的宽高
- @Autowired的使用:推荐对构造函数进行注释
- 添加任务
- 用nginx在window上搭建一个集群
- shell [] 常用命令
- 替换路径下所有文件中的字符串
- 项目配置的理解 Project Structre
- 从数据库取Blob数据
- MySql之视图
- SpringCloud学习_3(注册中心的高可用)