实例展示Spring的作用以及如何使用

news/2024/9/25 5:58:55/

Spring 是一个广泛应用于 Java 开发的开源框架,它主要有以下几个重要作用:

一、依赖注入(Dependency Injection)

作用:

  • 解耦组件之间的依赖关系,使得代码更易于维护和测试。比如在一个 Web 应用中,不同的业务逻辑层和数据访问层之间如果直接相互创建对象,会导致代码紧密耦合,一旦其中一个模块发生变化,可能会影响到其他多个模块。而通过 Spring 的依赖注入,可以在运行时动态地将对象注入到需要的地方,降低模块之间的耦合度。

实例:

  • 假设你有一个服务类 UserService 需要访问数据库来获取用户信息,通常情况下可能会在 UserService 中直接实例化一个数据访问对象 UserDao。但使用 Spring 后,可以将 UserDao 的实例注入到 UserService 中。
    public class UserService {private UserDao userDao;// 通过构造函数注入public UserService(UserDao userDao) {this.userDao = userDao;}public List<User> findAllUsers() {return userDao.findAll();}}

  • 在 Spring 的配置文件(如 XML 配置文件或 Java 配置类)中,配置 UserService 和 UserDao 的关系:
    <beans><bean id="userDao" class="com.example.UserDaoImpl"/><bean id="userService" class="com.example.UserService"><constructor-arg ref="userDao"/></bean></beans>

二、面向切面编程(AOP)

作用:

  • 将横切关注点(如日志记录、事务管理、安全检查等)从业务逻辑中分离出来,提高代码的可维护性和可重用性。例如,在一个企业级应用中,需要对多个业务方法进行日志记录,如果在每个方法中都添加日志代码,会导致代码重复且难以维护。使用 Spring AOP,可以将日志记录定义为一个切面,在不修改业务代码的情况下,自动应用到需要的地方。

实例:

  • 定义一个日志切面类:
    import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@Aspectpublic class LoggingAspect {private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);@Around("execution(* com.example.service..*.*(..))")public Object logMethodCall(ProceedingJoinPoint joinPoint) throws Throwable {logger.info("Entering method: {}", joinPoint.getSignature().toShortString());Object result = joinPoint.proceed();logger.info("Exiting method: {}", joinPoint.getSignature().toShortString());return result;}}

  • 在 Spring 配置文件中启用切面:
    <beans><!-- 其他 bean 定义 --><aop:aspectj-autoproxy/><bean class="com.example.LoggingAspect"/></beans>

三、事务管理

作用:

  • 简化数据库事务的处理。在处理数据库操作时,保证数据的一致性和完整性。例如,在一个银行转账的业务场景中,需要从一个账户扣款并向另一个账户存款,这两个操作必须要么同时成功,要么同时失败。Spring 的事务管理可以确保这种事务性操作的正确执行。

实例:

  • 使用 @Transactional 注解标记需要事务管理的方法:
    import org.springframework.transaction.annotation.Transactional;public class BankService {@Transactionalpublic void transferMoney(int fromAccountId, int toAccountId, double amount) {// 扣款逻辑deductMoney(fromAccountId, amount);// 存款逻辑depositMoney(toAccountId, amount);}private void deductMoney(int accountId, double amount) {// 数据库操作,从指定账户扣款}private void depositMoney(int accountId, double amount) {// 数据库操作,向指定账户存款}}

  • 在 Spring 配置文件中配置事务管理器:
    <beans><!-- 其他 bean 定义 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean></beans>

使用 Spring 框架通常需要以下步骤:

  1. 添加 Spring 依赖:
    • 在 Maven 或 Gradle 项目中添加 Spring 相关的依赖项。例如,对于 Maven 项目,可以在 pom.xml 文件中添加以下依赖:
    <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.11</version></dependency>

  1. 配置 Spring:
    • 可以使用 XML 配置文件或 Java 配置类来定义 bean 和配置 Spring 的各种功能。如上文示例中的 XML 配置文件,或者使用 Java 配置类:
    import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.example.UserDaoImpl;import com.example.UserService;@Configurationpublic class AppConfig {@Beanpublic UserDaoImpl userDao() {return new UserDaoImpl();}@Beanpublic UserService userService() {return new UserService(userDao());}}

  1. 启动 Spring 容器:
    • 在应用的入口处,创建 Spring 容器并获取所需的 bean。例如:
    import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);UserService userService = context.getBean(UserService.class);// 使用 userService 进行业务操作}}

http://www.ppmy.cn/news/1530154.html

相关文章

c++难点核心笔记(二)

系列文章目录 c难点&核心笔记(一) 继续接着上一章记录的重点内容包括函数&#xff0c;类和对象&#xff0c;指针和引用&#xff0c;C对象模型和this指针等内容&#xff0c;继续给大家分享&#xff01;&#xff01; 文章目录 系列文章目录友元全局函数做友元类做友元成员函…

Oracle数据库安装与SQL*Plus使用

一、实验过程 1、安装完数据库服务器程序后&#xff0c;查看系统服务启动状况并截图。 2、启动 SOL Plus工具,分别以SYS用户和 SYSTEM用户登录数据库&#xff0c;并解锁scott用户&#xff0c;用scott用户登录。每次登录完成后用show user命令查看当前用户&#xff0c;并截图。…

用 Pygame 实现一个乒乓球游戏

用 Pygame 实现一个乒乓球游戏 伸手需要一瞬间&#xff0c;牵手却要很多年&#xff0c;无论你遇见谁&#xff0c;他都是你生命该出现的人&#xff0c;绝非偶然。若无相欠&#xff0c;怎会相见。 引言 在这篇文章中&#xff0c;我将带领大家使用 Pygame 库开发一个简单的乒乓球…

【自动化测试】Appium Server如何安装和Appium Server安装困难的原因和解决方法以及常见的一些安装失败的错误和解决方法

引言 Appium Server安装过程时常出现问题&#xff0c;以下是安装Appium Server过程一些原因、常见错误和解决方法 文章目录 引言一、Appium Server如何安装1.1 Node.js 安装1.2 使用NPM安装Appium1.3 验证Appium安装1.4 运行Appium Server1.5 使用Appium Desktop&#xff08;可…

Django 解决跨域

一、配置 安装依赖 pip3 install django-cors-headers 修改配置 ALLOW_HOSTS [*] INSTALLD_APPS [ corsheaders ] MIDDLEWARE [ django.middleware.security.SecurityMiddleware, django.contrib.sessions.middleware.SessionMiddleware, corsheaders.middleware.CorsMiddl…

【有啥问啥】 Self-Play技术:强化学习中的自我进化之道

Self-Play技术&#xff1a;强化学习中的自我进化之道 在人工智能的快速发展中&#xff0c;强化学习&#xff08;Reinforcement Learning, RL&#xff09;已成为推动智能体自主学习与优化的关键力量。Self-Play技术&#xff0c;作为强化学习领域的一项前沿创新&#xff0c;通过…

星辰计划-深入理解kafka的消息存储和索引设计

消息存储 提到存储不得不说消息的读写&#xff0c;那么kafka他是如何读写数据的呢&#xff1f; 读取消息 1.通过debug(如何debug) 我们可以得到下面的调用栈&#xff0c;最终通过FileRecords来读取保存的数据 写入消息 1.通过debug(如何debug) 我们可以得到下面的调用栈&am…

P9235 [蓝桥杯 2023 省 A] 网络稳定性

*原题链接* 最小瓶颈生成树题&#xff0c;和货车运输完全一样。 先简化题意&#xff0c; 次询问&#xff0c;每次给出 &#xff0c;问 到 的所有路径集合中&#xff0c;最小边权的最大值。 对于这种题可以用kruskal生成树来做&#xff0c;也可以用倍增来写&#xff0c;但不…