@Autowired的操作:推荐对主函数进行注解转载

原创
小哥 3年前 (2022-12-30) 阅读数 12 #大杂烩

转自:http://www.cnblogs.com/acm-bingzi/p/springAutowired.html

@Autowired使用:建议对构造函数进行注释。

编写代码时,请使用@Autowired值得注意的是IDE警告报告如下:

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 @Autowired 2 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 @Autowired 5 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


所以一开始Spring建议,为什么添加成员变量final类型呢?

在线解释如下:spring配置默认值bean的scope是singleton也就是说,从一开始就有。通过设置bean的scope属性为prototype将对象声明为动态创建的。但如果你service本身是singleton,注射仅执行一次。

@Autowired它本身是一个单例模式,在程序启动时只执行一次,即使没有定义。final也不会在第二次初始化,因此final这没有道理。

也许是为了防止在程序运行时再次执行构造函数;

还是人们更容易理解其含义final它只在程序启动时初始化一次,在程序运行时不会更改。

然而,我仍然喜欢这种写作!

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除