Spring IOC与DI核心注解速查表
2026/7/8 19:25:54 网站建设 项目流程

一、IOC创建对象的4个核心注解

  1. @Controller- 用于标注控制器层组件(Controller层)
  2. @Service- 用于标注业务逻辑层组件(Service层)
  3. @Repository- 用于标注数据访问层组件(DAO层)
  4. @Component- 用于标注非三层架构的其他地方(通用组件)

原理:这些注解本质都是@Component的衍生注解,用于声明Bean并交由Spring容器管理


二、@Scope注解 - 控制对象作用域

@Scope("singleton")// 单例模式(默认)@Scope("prototype")// 多例模式

作用:控制Bean是单例还是多例,解决对象线程安全问题


三、XML配置 - 注解扫描生效

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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-scanbase-package="com.luo"/></beans>

关键点component-scan标签开启注解驱动,本质是BeanFactoryPostProcessor在操作


四、DI依赖注入注解

注解注入类型默认规则使用场景
@Value基本类型直接赋值字符串、数字等基本类型注入
@Autowired引用类型按类型注入(byType)同一类型Bean唯一时使用
@Resource引用类型按名字注入(byName)需要明确指定Bean名称时
@Qualifier配合@Autowired按名字注入同一接口多个实现类时精确定位

优势:相比XML配置,注解方式无需编写set方法,开发更高效


五、完整示例代码

@Service("userService")// 指定id为userService,默认是首字母小写的类名@Scope("singleton")publicclassUserServiceImplimplementsUserService{// 基本类型注入@Value("19")privateintage;// 引用类型自动注入(默认按类型)@AutowiredprivateUserDaouserDao;// 如果存在多个UserDao实现类,可配合@Qualifier使用// @Autowired// @Qualifier("userDaoImpl")// private UserDao userDao;@OverridepublicvoidfindUserById(){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实例化并管理其生命周期

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询