当前位置: 首页 > news >正文

IOC 注解方式详解

目标:掌握 Spring 中使用 注解(Annotation) 实现 IOC(控制反转)与 DI(依赖注入)的方法。


1️⃣ IOC 注解方式快速入门

1.1 依赖环境

与 XML 配置方式相同,只是 Bean 的定义改用注解完成。

1.2 编写接口与实现类

接口:

package com.qcbyjy.demo2;public interface UserService {void hello();
}

实现类:

package com.qcbyjy.demo2;import org.springframework.stereotype.Component;/*** 等价于:* <bean id="us" class="com.qcbyjy.demo2.UserServiceImpl" />*/
@Component(value = "us")
public class UserServiceImpl implements UserService {@Overridepublic void hello() {System.out.println("Hello IOC注解...");}
}

🔹 @Component 作用:让 Spring 自动管理这个类为 Bean。
如果不写 value,默认使用类名首字母小写作为 ID(例如 userServiceImpl)。


2️⃣ 开启注解扫描

applicationContext_anno.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 开启注解扫描 --><context:component-scan base-package="com.qcbyjy" /></beans>

3️⃣ 测试 IOC 注解方式

package com.qcbyjy.test;import com.qcbyjy.demo2.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo2 {@Testpublic void run1() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_anno.xml");UserService userService = (UserService) ac.getBean("us");userService.hello();}
}

运行结果:

Hello IOC注解...

4️⃣ 常用注解分类总结

(1)Bean 管理注解(创建 Bean)

注解作用层次说明
@Component通用组件类最基础的注解
@Controller表现层(Web 层)控制器组件
@Service业务逻辑层Service 组件
@Repository持久层Dao 组件

(2)依赖注入注解(注入 Bean)

注解用途
@Value注入普通类型属性(String、int、double 等)
@Autowired按类型自动装配(引用类型)
@Qualifier@Autowired 一起使用,按名称注入
@Resource按名称注入(Java 原生注解)

(3)Bean 作用域注解

注解说明
@Scope("singleton")单例(默认)
@Scope("prototype")多例,每次获取新对象

(4)生命周期注解

注解对应 XML 属性说明
@PostConstructinit-method初始化方法
@PreDestroydestroy-method销毁方法

单例 Bean 的销毁由 容器关闭 控制,多例 Bean 的销毁由 GC(垃圾回收) 控制。


5️⃣ 示例:综合使用注解

Car.java

package com.qcbyjy.demo3;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;import javax.annotation.PostConstruct;@Component(value = "c")
// @Scope("prototype") // 可切换作用域
public class Car {@Value("大奔2")private String cname;@Value("400000")private Double money;@Autowiredprivate Person person;@PostConstructpublic void init() {System.out.println("Car对象初始化完成...");}@Overridepublic String toString() {return "Car{" +"cname='" + cname + '\'' +", money=" + money +", person=" + person +'}';}
}

Person.java

package com.qcbyjy.demo3;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component(value = "person")
public class Person {@Value("张三")private String pname;@Overridepublic String toString() {return "Person{" + "pname='" + pname + '\'' + '}';}
}

测试类:

package com.qcbyjy.test;import com.qcbyjy.demo3.Car;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Demo3 {@Testpublic void run1() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext_anno.xml");Car car = (Car) ac.getBean("c");System.out.println(car);}
}

运行结果:

Car对象初始化完成...
Car{cname='大奔2', money=400000.0, person=Person{pname='张三'}}

6️⃣ IOC 纯注解方式(无 XML)

在微服务开发中,Spring Boot 就是基于这种“纯注解配置”的方式。

6.1 编写实体类

package com.qcbyjy.demo4;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class Order {@Value("北京")private String address;@Overridepublic String toString() {return "Order{" + "address='" + address + '\'' + '}';}
}

6.2 编写配置类(替代 XML)

package com.qcbyjy.demo4;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration              // 声明当前类为配置类
@ComponentScan("com.qcbyjy.demo4")  // 扫描包
public class SpringConfig {
}

6.3 编写测试类

package com.qcbyjy.test;import com.qcbyjy.demo4.Order;
import com.qcbyjy.demo4.SpringConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Demo4 {@Testpublic void run1() {ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);Order order = (Order) ac.getBean("order");System.out.println(order);}
}

运行结果:

Order{address='北京'}

7️⃣ 多配置类与 @Import、@Bean

7.1 多配置类拆分与引入

SpringConfig2.java

package com.qcbyjy.demo4;import org.springframework.context.annotation.Configuration;@Configuration
public class SpringConfig2 {
}

SpringConfig.java

package com.qcbyjy.demo4;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;@Configuration
@ComponentScan("com.qcbyjy.demo4")
@Import(SpringConfig2.class)   // 引入另一个配置类
public class SpringConfig {
}

7.2 使用 @Bean 注册第三方 Bean

package com.qcbyjy.demo4;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;import javax.sql.DataSource;@Configuration
@ComponentScan("com.qcbyjy.demo4")
@Import(SpringConfig2.class)
public class SpringConfig {/*** 创建连接池对象并交给 Spring 容器管理* 等价于 XML:** <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">*     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>*     <property name="url" value="jdbc:mysql:///spring_db"/>*     <property name="username" value="root"/>*     <property name="password" value="root"/>* </bean>*/@Bean(name = "dataSource")public DataSource createDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql:///spring_db");dataSource.setUsername("root");dataSource.setPassword("root");return dataSource;}
}

✅ 总结

注解作用
@Component / @Controller / @Service / @RepositoryBean 定义
@Value / @Autowired / @Qualifier / @Resource属性注入
@Scope / @PostConstruct / @PreDestroy生命周期管理
@Configuration / @ComponentScan / @Import / @Bean纯注解配置

🌱 小结:
从 XML 到注解再到纯注解配置,是 Spring 容器发展的必然趋势。
掌握注解式开发,是通向 Spring Boot 与微服务架构的基础!

http://www.dtcms.com/a/573257.html

相关文章:

  • LangFlow源码深度解析:Agent核心机制与工具化设计
  • gomobile build 成apk 遇到的几个问题
  • 化妆品购物网站开发的意义广州网络公司网络推广
  • 稳定的网站服务器租用七牛云存储 wordpress插件
  • 【SAA】SpringAI Alibaba学习笔记(一):SSE与WS的区别以及如何注入多个AI模型
  • 基于企业级建模平台Enterprise Architect的云地融合架构设计
  • 乡镇网站建设内容规划乐山网站制作设计公司
  • 【笔记】解决 “AssertionError: Torch not compiled with CUDA enabled“ 错误
  • 八股训练营第 7 天 | TCP连接如何确保可靠性?拥塞控制是怎么实现的?TCP流量控制是怎么实现的?UDP怎么实现可靠传输?
  • 清除BSS段(ZI段)
  • 数据库安全配置指导
  • 江苏南京建设局官方网站wordpress开发门户网站
  • 科学休息,我用AI写了个vscode养鱼插件:DevFish发布
  • Spring Boot 项目 GitLab CI/CD 自动构建并推送到 Harbor 教程
  • 彻底理解传统卷积,深度可分离卷积
  • 使用VSCode进行SSH远程连接时无法与xxx建立连接
  • 宁波建设工程报名网站陕西省住房与建设厅网站
  • Rust 练习册 6:生命周期与闭包
  • 公司网站开发的流程高端企业网站公司
  • 第二届中欧科学家论坛暨第七届人工智能与先进制造国际会议(AIAM 2025)在德国海德堡成功举办
  • 微硕WSF3085 MOSFET,汽车电动尾门升降强效驱动
  • 5 Prompt Engineering 高阶技巧:构建智能对话系统的核心技术
  • 汽车系统可靠性与技术融合:智能动力总成及机电一体化诊断
  • 网站建设对企业的重要性线上营销的优势和劣势
  • JavaScript 正则表达式全方位解析:从基础到实战
  • 工业相机成像核心参数解析,帧率与曝光时间的权衡关系
  • Kodiak Perps:Berachain 原生永续合约平台上线
  • 分布式版本控制系统Git的安装和使用
  • 用.echarts文件快速实现日历饼图
  • 影刀RPA一键生成竞品分析!AI智能监控,效率提升100倍[特殊字符]