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的基础介绍和核心特性。

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

咱们下一期见!

相关推荐
码兄科技5 小时前
Java AI智能体开发实战:从零构建智能对话系统指南
java·开发语言·人工智能
折哥的程序人生 · 物流技术专研6 小时前
第8篇:六大设计原则在工厂模式中的体现
java·设计模式·设计原则·工厂模式·编程进阶·扩充系列
小明bishe186 小时前
计算机毕业设计之基于JAVA的植物科普网站
java·spring boot·spring·架构·课程设计
Drone_xjw6 小时前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
r_oo_ki_e_6 小时前
Java Map 集合学习笔记
java·笔记·学习
SL-staff7 小时前
智慧园区2000+设备统一管理:JVS-IoT如何降低运维成本40%
java·开发语言·物联网·智慧园区·设备管理·运维优化·jvs-iot
咖啡八杯7 小时前
GoF设计模式——模板方法模式
java·后端·spring·设计模式
爱笑的源码基地8 小时前
一款全开源的信创云PACS影像云平台解决方案,支持多模态医学影像处理(CT/MR/DR/超声/病理等)
java·源码·国产化·pacs·云影像·区域pacs
我命由我123458 小时前
Android 开发问题:ClickableSpan 的点击事件没有生效
java·java-ee·android studio·android jetpack·android-studio·android runtime
2zcode9 小时前
基于MATLAB图像处理的饮料瓶灌装液位检测系统设计与实现
开发语言·图像处理·matlab