Spring的自动装配机制表现为:当需要某个对象时,可以使用特定的语法,而Spring就会尝试从容器找到合适的值,并赋值到对应的位置!
最典型的表现就是在类的属性上添加@Autowired
注解,Spring就会尝试从容器中找到合适的值为这个属性赋值!
例如有如下代码:
SpringConfig.java
package spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("cn.tedu.spring")
public class SpringConfig {
}
UserMapper.java
package spring;
import org.springframework.stereotype.Repository;
@Repository
public class UserMapper {
public void insert() {
System.out.println("UserMapper.insert() >> 将用户数据写入到数据库中……");
}
}
UserController.java
package spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
@Autowired // 注意:此处使用了自动装配的注解
private UserMapper userMapper;
public void reg() {
System.out.println("UserController.reg() >> 控制器即将执行用户注册……");
userMapper.insert();
}
}
SpringRunner.javaq
package cn.tedu.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringRunner {
public static void main(String[] args) {
// 1. 加载Spring
AnnotationConfigApplicationContext ac
= new AnnotationConfigApplicationContext(SpringConfig.class);
// 2. 从Spring中获取对象
UserController userController
= ac.getBean("userController", UserController.class);
// 3. 测试使用对象,以便于观察是否获取到了有效的对象
userController.reg();
// 4. 关闭
ac.close();
}
}
关于@Autowired
的装配机制:
首先,会根据需要装配的数据的类型在Spring容器中查找匹配的Bean(对象)的数量,当数量为:
- 0个:判断
@Autowired
注解的required
属性的值- 当
required=true
时:装配失败,启动项目时即报告异常 - 当
required=false
时:放弃自动装配,不会报告异常- 后续当使用到此属性时,会出现
NullPointerException
- 后续当使用到此属性时,会出现
- 当
- 1个:直接装配,且装配成功
- 多个:自动尝试按照名称实现装配(属性的名称与Spring Bean的名称)
- 存在与属性名称匹配的Spring Bean:装配成功
- 不存在与属性名称匹配的Spring Bean:装配失败,启动项目时即报告异常
另外,使用@Resource
注解也可以实现自动装配(此注解是javax
包中的),其装配机制是先尝试根据名称来装配,如果失败,再尝试根据类型装配!