Spring 的 Annotation 自动装配是利用注解来自动完成 Bean 的依赖注入,无需在 XML 中进行大量繁琐的配置,极大地简化了开发流程。
想象一家餐厅,餐厅里有厨师、服务员、收银员等角色(相当于 Bean)。老板(Spring 容器)通过查看员工的技能标签(注解),自动将合适的员工安排到对应的岗位(依赖注入),而不需要老板一个个手动去安排。
@Component
及其衍生注解(重点)@Component
是一个通用的注解,用于将类标记为 Spring 管理的 Bean。它有三个常用的衍生注解:@Service
、@Repository
和 @Controller
,它们在语义上有更明确的分工。
@Service
:通常用于标记业务逻辑层的类。@Repository
:用于标记数据访问层的类,如 DAO 类。@Controller
:用于标记控制器层的类,处理 HTTP 请求。在餐厅中,@Service
就像是餐厅的厨师长,负责管理和安排菜品的制作流程(业务逻辑);@Repository
如同餐厅的食材仓库管理员,负责食材的存储和取用(数据访问);@Controller
则是餐厅的服务员,接收顾客的订单(HTTP 请求)并将其传递给厨师长。
// 业务逻辑层
@Service
public class RestaurantService {
// 业务逻辑方法
}
// 数据访问层
@Repository
public class DishRepository {
// 数据访问方法
}
// 控制器层
@Controller
public class RestaurantController {
// 处理请求的方法
}
@Autowired
(重点)@Autowired
用于自动注入依赖的 Bean。Spring 会根据类型在容器中查找匹配的 Bean 并注入。
在餐厅里,厨师长(RestaurantService
)需要使用各种厨具(DishRepository
)来制作菜品。通过 @Autowired
,老板(Spring 容器)会自动将合适的厨具(Bean)提供给厨师长。
@Service
public class RestaurantService {
@Autowired
private DishRepository dishRepository;
// 使用 dishRepository 进行业务操作
}
@Qualifier
当存在多个同类型的 Bean 时,@Autowired
无法确定注入哪个 Bean,此时可以使用 @Qualifier
来指定具体要注入的 Bean 的名称。
餐厅里有多种不同品牌的烤箱(同类型的 Bean),厨师长(RestaurantService
)需要指定使用某个特定品牌的烤箱(通过 @Qualifier
指定 Bean 名称)来制作特定的菜品。
@Service
public class RestaurantService {
@Autowired
@Qualifier("specificOven")
private Oven oven;
// 使用指定的 oven 进行业务操作
}
@Resource
@Resource
是 JSR-250 标准的注解,它可以根据名称或类型进行注入。默认先根据名称查找,如果找不到再根据类型查找。
在餐厅中,服务员(RestaurantController
)需要使用特定的菜单(Bean)来为顾客提供服务。@Resource
可以帮助服务员准确地找到所需的菜单。
@Controller
public class RestaurantController {
@Resource(name = "specialMenu")
private Menu menu;
// 使用 menu 处理请求
}
@Value
@Value
用于注入外部配置文件中的值,如属性文件(.properties
)或 YAML 文件中的值。
餐厅的营业时间是一个配置项,存储在外部配置文件中。服务员(RestaurantController
)可以通过 @Value
获取这个营业时间,并告知顾客。
@Controller
public class RestaurantController {
@Value("${restaurant.openTime}")
private String openTime;
// 使用 openTime 处理请求
}
@Service
public class RestaurantService {
private final DishRepository dishRepository;
@Autowired
public RestaurantService(DishRepository dishRepository) {
this.dishRepository = dishRepository;
}
}
@Service
、@Repository
和 @Controller
,提高代码的可读性和可维护性。@Lazy
注解来解决部分循环依赖问题。@Qualifier
或 @Primary
注解来明确指定要注入的 Bean。Spring Boot 基于 Spring 的 Annotation 自动装配,提供了更强大的自动配置功能。学习 Spring Boot 的自动配置原理和使用方法,可以进一步简化开发流程。
了解如何结合 Annotation 实现面向切面编程(AOP),如使用 @Aspect
、@Before
、@After
等注解来实现日志记录、事务管理等功能。
学习 Spring Security 中使用的注解,如 @PreAuthorize
、@PostAuthorize
等,用于实现基于注解的权限控制。
掌握 Spring Data JPA 中使用的注解,如 @Entity
、@Id
、@GeneratedValue
等,用于简化数据库操作。
通过掌握 Spring 中 Annotation 自动装配的知识,可以提高开发效率,使代码更加简洁和易于维护。同时,为后续学习 Spring Boot、AOP、Security 等高级知识打下坚实的基础。