一、IOC创建对象的4个核心注解
- @Controller - 用于标注控制器层组件(Controller层)
- @Service - 用于标注业务逻辑层组件(Service层)
- @Repository - 用于标注数据访问层组件(DAO层)
- @Component - 用于标注非三层架构的其他地方(通用组件)
原理 :这些注解本质都是
@Component的衍生注解,用于声明Bean并交由Spring容器管理
二、@Scope注解 - 控制对象作用域
java
@Scope("singleton") // 单例模式(默认)
@Scope("prototype") // 多例模式
作用:控制Bean是单例还是多例,解决对象线程安全问题
三、XML配置 - 注解扫描生效
xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描指定包下的注解 -->
<context:component-scan base-package="com.luo" />
</beans>
关键点 :component-scan标签开启注解驱动,本质是BeanFactoryPostProcessor在操作
四、DI依赖注入注解
| 注解 | 注入类型 | 默认规则 | 使用场景 |
|---|---|---|---|
| @Value | 基本类型 | 直接赋值 | 字符串、数字等基本类型注入 |
| @Autowired | 引用类型 | 按类型注入(byType) | 同一类型Bean唯一时使用 |
| @Resource | 引用类型 | 按名字注入(byName) | 需要明确指定Bean名称时 |
| @Qualifier | 配合@Autowired | 按名字注入 | 同一接口多个实现类时精确定位 |
优势:相比XML配置,注解方式无需编写set方法,开发更高效
五、完整示例代码
java
@Service("userService") // 指定id为userService,默认是首字母小写的类名
@Scope("singleton")
public class UserServiceImpl implements UserService {
// 基本类型注入
@Value("19")
private int age;
// 引用类型自动注入(默认按类型)
@Autowired
private UserDao userDao;
// 如果存在多个UserDao实现类,可配合@Qualifier使用
// @Autowired
// @Qualifier("userDaoImpl")
// private UserDao userDao;
@Override
public void findUserById() {
userDao.findUserById();
System.out.println("UserService!!!!");
}
}
六、快速记忆口诀
IOC四兄弟 :Controller、Service、Repository、Component
Scope控单例 :singleton默认,prototype多例
DI四剑客 :Value基本型,Autowired类型,Resource名字,Qualifier配合
XML扫注解 :component-scan包路径
修改BeanID:@Component("自定义名称")
七、原理补充(理解性记忆)
所有注解生效的前提是Spring容器启动时通过<context:component-scan>扫描包路径,将带有注解的类注册为BeanDefinition,再由BeanFactory实例化并管理其生命周期