Java企业级开发系列(1)

Spring Framework入门指南:从零开始构建企业级应用 🚀

🎯 掌握Spring框架,助你成为Java企业级开发高手!

在上一篇文章中,我们学习了Java入门系列的最后一篇文章--Java反射机制。今天开始,让我们一起深入探索Spring框架,这个Java领域最受欢迎的企业级开发框架!

考虑到相关内容较多,咱们这个系列分为四个部分进行更新!

废话不多说,开始第一部分!

1. Spring框架简介 📚

1.1 什么是Spring Framework?

Spring Framework是一个轻量级的开源应用框架,它为开发Java应用提供了全面的基础设施支持。Spring的核心特性是依赖注入(DI)和面向切面编程(AOP)。

1.2 为什么选择Spring?

  • 🔸 模块化设计,按需使用
  • 🔸 松耦合,易于测试
  • 🔸 强大的生态系统
  • 🔸 活跃的社区支持
  • 🔸 广泛的企业应用

1.3 Spring的核心模块

复制代码
spring-core
├── spring-beans       # Bean容器和依赖注入
├── spring-context     # 应用上下文,邮件,定时任务等
├── spring-aop         # 面向切面编程
├── spring-jdbc        # 数据库访问
├── spring-orm        # 对象关系映射
├── spring-web        # Web开发基础
└── spring-webmvc     # Web MVC框架

2. 快速开始 🚀

2.1 环境准备

首先,在Maven项目中添加Spring依赖:

xml 复制代码
<dependencies>
    <!-- Spring核心依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.23</version>
    </dependency>
    
    <!-- Spring Web MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.23</version>
    </dependency>
    
    <!-- 数据库相关 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.23</version>
    </dependency>
    
    <!-- Lombok(可选) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

2.2 第一个Spring应用

创建一个简单的Spring应用,展示依赖注入的基本用法:

java 复制代码
// 用户实体
@Data
@AllArgsConstructor
public class User {
    private Long id;
    private String username;
    private String email;
}

// 用户服务接口
public interface UserService {
    User getUserById(Long id);
    void createUser(User user);
}

// 用户服务实现
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public User getUserById(Long id) {
        log.info("获取用户信息: {}", id);
        return userRepository.findById(id);
    }
    
    @Override
    public void createUser(User user) {
        log.info("创建用户: {}", user);
        userRepository.save(user);
    }
}

// 应用配置类
@Configuration
@ComponentScan("com.example.demo")
public class AppConfig {
    @Bean
    public UserRepository userRepository() {
        return new UserRepositoryImpl();
    }
}

// 主类
public class MainApplication {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        UserService userService = context.getBean(UserService.class);
        
        User user = new User(1L, "张三", "zhangsan@example.com");
        userService.createUser(user);
        
        User foundUser = userService.getUserById(1L);
        System.out.println("找到用户:" + foundUser);
    }
}

3. Spring核心特性详解 💡

3.1 依赖注入(DI)

Spring提供了多种依赖注入方式:

java 复制代码
// 1. 构造器注入(推荐)
@Service
public class OrderService {
    private final UserService userService;
    private final PaymentService paymentService;
    
    @Autowired
    public OrderService(UserService userService, PaymentService paymentService) {
        this.userService = userService;
        this.paymentService = paymentService;
    }
}

// 2. Setter注入
@Service
public class ProductService {
    private InventoryService inventoryService;
    
    @Autowired
    public void setInventoryService(InventoryService inventoryService) {
        this.inventoryService = inventoryService;
    }
}

// 3. 字段注入(不推荐)
@Service
public class CartService {
    @Autowired
    private ProductService productService;
}

3.2 面向切面编程(AOP)

AOP允许我们将横切关注点(如日志、事务)从业务逻辑中分离出来:

java 复制代码
// 日志切面
@Aspect
@Component
@Slf4j
public class LoggingAspect {
    
    @Around("@annotation(LogExecutionTime)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        
        log.info("方法 {} 执行耗时: {}ms",
            joinPoint.getSignature().getName(),
            (endTime - startTime));
            
        return result;
    }
    
    @AfterThrowing(pointcut = "execution(* com.example.demo.service.*.*(..))",
                   throwing = "ex")
    public void logError(JoinPoint joinPoint, Exception ex) {
        log.error("方法 {} 执行异常: {}",
            joinPoint.getSignature().getName(),
            ex.getMessage());
    }
}

// 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}

// 使用示例
@Service
public class UserService {
    @LogExecutionTime
    public User findById(Long id) {
        // 业务逻辑
    }
}

系列的第一部分,到此暂告一段落,内容包含了Spring的基础介绍和核心特性。

如果你觉得这篇文章有帮助,欢迎点赞转发,也期待在评论区看到你的想法和建议!👇

咱们下一期见!

相关推荐
铁蛋AI编程实战1 分钟前
通义千问 3.5 Turbo GGUF 量化版本地部署教程:4G 显存即可运行,数据永不泄露
java·人工智能·python
HyperAI超神经6 分钟前
在线教程|DeepSeek-OCR 2公式/表格解析同步改善,以低视觉token成本实现近4%的性能跃迁
开发语言·人工智能·深度学习·神经网络·机器学习·ocr·创业创新
晚霞的不甘12 分钟前
CANN 编译器深度解析:UB、L1 与 Global Memory 的协同调度机制
java·后端·spring·架构·音视频
SunnyDays101114 分钟前
使用 Java 冻结 Excel 行和列:完整指南
java·冻结excel行和列
R_.L16 分钟前
【QT】常用控件(按钮类控件、显示类控件、输入类控件、多元素控件、容器类控件、布局管理器)
开发语言·qt
Zach_yuan25 分钟前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络
摇滚侠25 分钟前
在 SpringBoot 项目中,开发工具使用 IDEA,.idea 目录下的文件需要提交吗
java·spring boot·intellij-idea
云姜.30 分钟前
java多态
java·开发语言·c++
李堇33 分钟前
android滚动列表VerticalRollingTextView
android·java
CoderCodingNo39 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法