写在前面得话

学习@Autowired 之前建议先学会使用 byType 和 byName

@Autowired 详解

首先要知道另一个东西,default-autowire,它是在 xml 文件中进行配置的,可以设置为 byName、byType、constructor 和 autodetect;比如 byName,不用显式的在 bean 中写出依赖的对象,它会自动的匹配其它 bean 中 id 名与本 bean 的 set**相同的,并自动装载。
@Autowired 是用在 JavaBean 中的注解,通过 byType 形式,用来给指定的字段或方法注入所需的外部资源。
两者的功能是一样的,就是能减少或者消除属性或构造器参数的设置,只是配置地方不一样而已。
autowire 四种模式的区别

先看一下 bean 实例化和@Autowired 装配过程:
一切都是从 bean 工厂的 getBean 方法开始的,一旦该方法调用总会返回一个 bean 实例,无论当前是否存在,不存在就实例化一个并装配,否则直接返回。(Spring MVC 是在什么时候开始执行 bean 的实例化过程的呢?其实就在组件扫描完成之后)

实例化和装配过程中会多次递归调用 getBean 方法来解决类之间的依赖。

Spring 几乎考虑了所有可能性,所以方法特别复杂但完整有条理。

@Autowired 最终是根据类型来查找和装配元素的,但是我们设置了后会影响最终的类型匹配查找。因为在前面有根据 BeanDefinition 的 autowire 类型设置 PropertyValue 值得一步,其中会有新实例的创建和注册。就是那个 autowireByName 方法。

下面通过@Autowired 来说明一下用法

Setter 方法中的 @Autowired

你可以在 JavaBean 中的 setter 方法中使用 @Autowired 注解。当 Spring 遇到一个在 setter 方法中使用的 @Autowired 注解,它会在方法中执行 byType 自动装配。
这里是 TextEditor.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker( ) {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}

下面是另一个依赖的类文件 SpellChecker.java 的内容:

1
2
3
4
5
6
7
8
9
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}

下面是 MainApp.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}

下面是配置文件 Beans.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>

</beans>

一旦你已经完成的创建了源文件和 bean 配置文件,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:

Inside SpellChecker constructor.
Inside checkSpelling.

属性中的 @Autowired

你可以在属性中使用 @Autowired 注解来除去 setter 方法。当时使用 为自动连接属性传递的时候,Spring 会将这些传递过来的值或者引用自动分配给那些属性。所以利用在属性中 @Autowired 的用法,你的 TextEditor.java 文件将变成如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
@Autowired
private SpellChecker spellChecker;
public TextEditor() {
System.out.println("Inside TextEditor constructor." );
}
public SpellChecker getSpellChecker( ){
return spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}

下面是配置文件 Beans.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>

</beans>

一旦你在源文件和 bean 配置文件中完成了上面两处改变,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:

Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.

构造函数中的 @Autowired

你也可以在构造函数中使用 @Autowired。一个构造函数 @Autowired 说明当创建 bean 时,即使在 XML 文件中没有使用 元素配置 bean ,构造函数也会被自动连接。让我们检查一下下面的示例。
这里是 TextEditor.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}

下面是配置文件 Beans.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:annotation-config/>

<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
</bean>

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>

</beans>

一旦你在源文件和 bean 配置文件中完成了上面两处改变,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:

Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.

@Autowired 的(required=false)选项

默认情况下,@Autowired 注解意味着依赖是必须的,它类似于 @Required 注解,然而,你可以使用 @Autowired 的 (required=false) 选项关闭默认行为。
即使你不为 age 属性传递任何参数,下面的示例也会成功运行,但是对于 name 属性则需要一个参数。你可以自己尝试一下这个示例,因为除了只有 Student.java 文件被修改以外,它和 @Required 注解示例是相似的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class Student {
private Integer age;
private String name;
@Autowired(required=false)
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Autowired
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

其他

@Autowired 注释应用于具有任意名称和多个参数的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MovieRecommender {

private MovieCatalog movieCatalog;

private CustomerPreferenceDao customerPreferenceDao;

@Autowired
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}

// ...
}

您也可以将@Autowired 应用于字段,或者将其与构造函数混合,如以下示例所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MovieRecommender {

private final CustomerPreferenceDao customerPreferenceDao;

@Autowired
private MovieCatalog movieCatalog;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}

// ...
}

将@Autowired 注释添加到需要该类型数组的字段或方法,则 spring 会从 ApplicationContext 中搜寻符合指定类型的所有 bean,如以下示例所示:

1
2
3
4
5
6
7
public class MovieRecommender {

@Autowired
private MovieCatalog[] movieCatalogs;

// ...
}

数组可以,我们可以马上举一反三,那容器也可以吗,答案是肯定的,下面是 set 以及 map 的例子:

1
2
3
4
5
6
7
8
9
10
11
public class MovieRecommender {

private Set<MovieCatalog> movieCatalogs;

@Autowired
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}

// ...
}
1
2
3
4
5
6
7
8
9
10
11
public class MovieRecommender {

private Map<String, MovieCatalog> movieCatalogs;

@Autowired
public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}

// ...
}

以上就是@Autowired 注解的主要使用方式,经常使用 spring 的话应该对其中常用的几种不会感到陌生。

@Autowired 装配不成功的几种情况?

没有加@Component 注解

在类上面忘了加@Controller、@Service、@Component、@Repository 等注解,spring 就无法完成自动装配的功能,例如:

1
2
3
4
5
6
7
public class UserService {
@Autowired
private IUser user;
public void test() {
user.say();
}
}

这种情况应该是最常见的错误了,不会因为你长得帅,就不会犯这种低级的错误。

注入 Filter 或 Listener

web 应用启动的顺序是:listener->filter->servlet。

img

接下来看看这个案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class UserFilter implements Filter {
@Autowired
private IUser user;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
user.say();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
}
@Override
public void destroy() {
}
}
1
2
3
4
5
6
7
8
9
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean() {
bean = new FilterRegistrationBean();
bean.setFilter(new UserFilter());
bean.addUrlPatterns("/*");
return bean;
}
}

程序启动会报错,tomcat 也无法正常启动???什么原因??

众所周知,springmvc 的启动是在 DisptachServlet 里面做的,而它是在 listener 和 filter 之后执行。如果我们想在 listener 和 filter 里面@Autowired 某个 bean,肯定是不行的,因为 filter 初始化的时候,此时 bean 还没有初始化,无法自动装配。

如果工作当中真的需要这样做,我们该如何解决这个问题呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class UserFilter  implements Filter {
private IUser user;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(
filterConfig.getServletContext());
this.user = ((IUser)(applicationContext.getBean("user1")));
user.say();
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

}

@Override
public void destroy() {

}
}

答案是使用 WebApplicationContextUtils.getWebApplicationContext 获取当前的 ApplicationContext,再通过它获取到 bean 实例。

注解未被@ComponentScan 扫描

通常情况下,@Controller、@Service、@Component、@Repository、@Configuration 等注解,是需要通过@ComponentScan 注解扫描,收集元数据的。

但是,如果没有加@ComponentScan 注解,或者@ComponentScan 注解扫描的路径不对,或者路径范围太小,会导致有些注解无法收集,到后面无法使用@Autowired 完成自动装配的功能。

有个好消息是,在 springboot 项目中,如果使用了@SpringBootApplication 注解,它里面内置了@ComponentScan 注解的功能。

循环依赖问题

如果 A 依赖于 B,B 依赖于 C,C 又依赖于 A,这样就形成了一个死循环。

img

spring 的 bean 默认是单例的,如果单例 bean 使用@Autowired 自动装配,大多数情况,能解决循环依赖问题。

但是如果 bean 是多例的,会出现循环依赖问题,导致 bean 自动装配不了。

还有有些情况下,如果创建了代理对象,即使 bean 是单例的,依然会出现循环依赖问题。

@Autowired 和@Resouce 的区别

@Autowired 功能虽说非常强大,但是也有些不足之处。比如:比如它跟 spring 强耦合了,如果换成了 JFinal 等其他框架,功能就会失效。而@Resource 是 JSR-250 提供的,它是 Java 标准,绝大部分框架都支持。

除此之外,有些场景使用@Autowired 无法满足的要求,改成@Resource 却能解决问题。接下来,我们重点看看@Autowired 和@Resource 的区别。

  • @Autowired 默认按 byType 自动装配,而@Resource 默认 byName 自动装配。
  • @Autowired 只包含一个参数:required,表示是否开启自动准入,默认是 true。而@Resource 包含七个参数,其中最重要的两个参数是:name 和 type。
  • @Autowired 如果要使用 byName,需要使用@Qualifier 一起配合。而@Resource 如果指定了 name,则用 byName 自动装配,如果指定了 type,则用 byType 自动装配。
  • @Autowired 能够用在:构造器、方法、参数、成员变量和注解上,而@Resource 能用在:类、成员变量和方法上。
  • @Autowired 是 spring 定义的注解,而@Resource 是 JSR-250 定义的注解。

此外,它们的装配顺序不同。

@Autowired 的装配顺序如下:

img

@Resource 的装配顺序如下:

1.如果同时指定了 name 和 type:

img

如果指定了 name:

img

如果指定了 type:

img

如果既没有指定 name,也没有指定 type:

img