资讯动态

Spring 02:注解驱动开发

发布时间:2026/9/18 15:33:53 来源:尧图企业网站定制
引言在Spring框架中IOC控制反转和DI依赖注入是核心思想。通过注解开发我们可以大幅简化Spring配置提高开发效率。本文将深入探讨Spring IOC/DI的注解开发模式并结合实际案例展示如何管理第三方框架如Mybatis和Junit。一、管理第三方Bean为避免硬编码将数据库配置提取到properties文件# jdbc.properties jdbc.drivercom.mysql.jdbc.Driver jdbc.urljdbc:mysql://localhost:3306/spring_db jdbc.usernameroot jdbc.passwordroot一Duridpom.xml中添加依赖dependency groupIdcom.alibaba/groupId artifactIddruid/artifactId version1.1.16/version /dependency在applicationContext.xml配置文件中添加DruidDataSource的配置?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd !--管理DruidDataSource对象-- bean classcom.alibaba.druid.pool.DruidDataSource property namedriverClassName valuecom.mysql.jdbc.Driver/ property nameurl valuejdbc:mysql://localhost:3306/spring_db/ property nameusername valueroot/ property namepassword valueroot/ /bean /beansdriverClassName:数据库驱动url:数据库连接地址username:数据库连接用户名password:数据库连接密码setter注入数据库连接的四要素要和自己使用的数据库信息一致。二C3P0pom.xml中添加依赖dependency groupIdc3p0/groupId artifactIdc3p0/artifactId version0.9.1.2/version /dependency dependency groupIdmysql/groupId artifactIdmysql-connector-java/artifactId version5.1.47/version /dependencyDruid和C3P0在没有导入mysql驱动包的前提下一个没报错一个报错说明Druid在初始化的时候没有去加载驱动而C3P0刚好相反Druid程序运行虽然没有报错但是当调用DruidDataSource的getConnection()方法获取连接的时候也会报找不到驱动类的错误配置第三方bean通过setter方法注入ComboPooledDataSourcebean iddataSource classcom.mchange.v2.c3p0.ComboPooledDataSource property namedriverClass valuecom.mysql.jdbc.Driver/ property namejdbcUrl valuejdbc:mysql://localhost:3306/spring_db/ property nameuser valueroot/ property namepassword valueroot/ property namemaxPoolSize value1000/ /bean三总结完成durid或C3P0后从IOC容器中获取对应的bean对象之后即可运行程序public class App { public static void main(String[] args) { ApplicationContext ctx new ClassPathXmlApplicationContext(applicationContext.xml); DataSource dataSource (DataSource) ctx.getBean(dataSource); System.out.println(dataSource); } }Druid vs C3P0 对比特性DruidC3P0提供方阿里开源JDBC连接池性能高较低驱动加载时机延迟加载运行时初始化时加载监控功能强大的监控和统计功能基本功能二、加载Properties配置文件Spring配置加载context:property-placeholder locationclasspath:jdbc.properties system-properties-modeNEVER/加载方式对比单个文件locationjdbc.properties多个文件locationjdbc.properties,jdbc2.properties通配符location*.properties类路径locationclasspath:*.properties类路径含依赖locationclasspath*:*.properties三、Spring核心容器这里所说的核心容器可以把它简单的理解为ApplicationContext。一容器创建传统 XML 配置容器// 类路径加载推荐 ApplicationContext ctx new ClassPathXmlApplicationContext(applicationContext.xml); // 文件系统加载不推荐使用当项目的位置发生变化后,代码也需要跟着改,耦合度较高 ApplicationContext ctx new FileSystemXmlApplicationContext(D:/config/applicationContext.xml);现代注解配置容器AnnotationConfigApplicationContext是现代 Spring 应用开发中纯注解配置方式的核心入口完全取代了传统的 XML 配置方式。// 加载配置类初始化容器 ApplicationContext ctx new AnnotationConfigApplicationContext(SpringConfig.class);ClassPathXmlApplicationContext是加载XML配置文件AnnotationConfigApplicationContext是加载配置类二获取Bean的三种方式// 1. 按名称获取需强转 BookDao dao (BookDao) ctx.getBean(bookDao); // 2. 按名称类型获取解决强转但多一个参数 BookDao dao ctx.getBean(bookDao, BookDao.class); // 3. 按类型获取需确保IOC容器中该类型对应的bean对象只能有一个 BookDao dao ctx.getBean(BookDao.class);三容器类层次结构只需要知晓容器的最上级的父接口为BeanFactory即可四BeanFactory特性BeanFactoryApplicationContext加载时机延迟加载使用时创建立即加载启动时创建功能完整性基础功能扩展功能AOP等使用场景资源受限环境大多数应用场景五小结BeanFactory是IoC容器的顶层接口初始化BeanFactory对象时加载的bean延迟加载ApplicationContext接口是Spring容器的核心接口初始化时bean立即加载ApplicationContext接口提供基础的bean操作相关方法通过其他接口扩展其功能ApplicationContext接口常用初始化类ClassPathXmlApplicationContext(常用)FileSystemXmlApplicationContext四、注解开发一核心注解特性ComponentControllerServiceRepository继承关系基础注解派生自Component派生自Component派生自Component使用场景通用组件MVC控制器业务逻辑层数据访问层语义含义通用Spring组件处理用户请求业务逻辑服务数据存储库特殊功能无处理HTTP请求事务管理异常转换层级位置任意层表现层业务层持久层典型用途工具类、配置类REST控制器业务逻辑实现DAO实现类虽然技术上可以全部使用Component但使用特定注解有利于明确标识组件在架构中的角色提高代码可读性方便针对特定层进行切面编程以及进行如Repository的异常转换功能。处理HTTP请求 →Controller- 系统的门面处理用户交互实现业务逻辑 →Service- 业务逻辑的大脑实现核心功能数据库访问 →Repository- 数据访问的手与持久化存储交互通用工具类 →Component- 通用的工具提供辅助功能二纯注解配置Configuration ComponentScan(com.example) PropertySource(classpath:app.properties) public class AppConfig { }特性ConfigurationComponentScan主要作用标识配置类自动扫描并注册组件替代方案XML配置文件 (beans标签)XML组件扫描 (context:component-scan)使用位置类级别类级别常与Configuration一起使用核心功能定义Bean和配置发现和管理组件是否必须纯注解开发必须可选但强烈推荐使用典型使用场景定义第三方Bean、全局配置自动注册业务组件,Configuration设置该类为spring配置类使用类替换applicationContext.xml文件value默认定义bean的idComponentScan设置spring配置类扫描路径用于加载使用注解格式定义的beanvalue默认扫描路径此路径可以逐层向下扫描此注解只能添加一次多个数据请用数组格式ComponentScan({com.example.service,com.example.dao})三Bean作用域与生命周期Repository Scope(prototype) // 默认为singleton public class UserDaoImpl { PostConstruct // 设置该方法为初始化方法 public void init() { System.out.println(Bean初始化); } PreDestroy // 设置该方法为销毁方法 public void destroy() { System.out.println(Bean销毁); } }名称Scope类型类注解位置类定义上方作用设置该类创建对象的作用范围可用于设置创建出的bean是否为单例对象属性value默认定义bean作用范围默认值singleton单例可选值prototype非单例xml属性与注解的关系大致如下四依赖注入Service public class UserServiceImpl { Autowired // 按类型注入 private UserDao userDao; Autowired Qualifier(mainDataSource) // 按名称注入 private DataSource dataSource; Value(${app.timeout}) // 注入简单值 private int timeout; }注解名称类型应用位置主要作用关键属性Autowired属性/方法/方法形参注解属性定义上方setter方法上方方法形参前面自动装配引用类型根据类型自动注入依赖对象required是否必须注入(true/false默认true)Qualifier属性/方法注解属性定义上方setter方法上方精确指定Bean名称解决同类型多个Bean的歧义value指定要注入的Bean IDValue属性/方法注解属性定义上方setter方法上方注入简单类型值注入基本类型、字符串或表达式结果value要注入的值或表达式(如${property})PropertySource类注解类定义上方加载外部配置将properties文件加载到Spring环境value配置文件名或数组(支持classpath:前缀)五、整合第三方框架一 管理第三方BeanConfiguration public class DataSourceConfig { Bean public DataSource dataSource() { DruidDataSource ds new DruidDataSource(); ds.setDriverClassName(com.mysql.jdbc.Driver); // 其他配置... return ds; } }二整合MybatisConfiguration public class MybatisConfig { Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setTypeAliasesPackage(com.example.domain); return factory.getObject(); } }三整合JunitRunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classes {AppConfig.class}) public class UserServiceTest { Autowired private UserService userService; Test public void testFindUser() { User user userService.findById(1); assertNotNull(user); } }注解应用位置主要作用关键属性适用场景Bean配置类中的方法上显式声明 Spring Bean将方法返回对象注册为 Spring Beanname/valueBean 名称initMethod初始化方法destroyMethod销毁方法管理第三方库组件复杂初始化逻辑条件化创建 BeanImport配置类上模块化配置组合导入其他配置类或组件value要导入的类数组支持配置类、组件类、ImportSelector 等大型应用配置拆分特性模块化自动配置机制RunWithJUnit 测试类上指定测试运行器定制测试执行环境value测试运行器类如SpringJUnit4ClassRunnerSpring 集成测试需要容器环境的测试定制测试行为ContextConfigurationJUnit 测试类上加载 Spring 配置为测试提供应用上下文classes配置类数组locations配置文件路径inheritLocations继承配置单元测试依赖注入集成测试环境多配置组合测试六、总结功能XML配置注解定义BeanbeanComponent及其衍生作用域scope属性Scope生命周期init-method/destroyPostConstruct/PreDestroy依赖注入propertyAutowired/Value第三方Bean管理beanBean配置文件加载context:property-placeholderPropertySource

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价