0


Idea 创建 Spring 项目(保姆级)

描述信息

最近卷起来,系统学习Spring;俗话说:万事开头难;创建一个Spring项目在网上找了好久没有找到好的方式;摸索了半天产出如下文档。

在 Idea 中新建项目

填写信息如下

生成项目目录结构

pom添加依赖

  1. <dependencies>
  2. <!-- spring-core: 包含Spring框架的核心功能,如IoC(控制反转)和DI(依赖注入)的基本功能。该模块提供了Spring框架的基础架构 -->
  3. <dependency>
  4. <groupId>org.springframework</groupId>
  5. <artifactId>spring-core</artifactId>
  6. <version>5.3.31</version>
  7. </dependency>
  8. <!-- spring-context: 提供更广泛的应用上下文(Application Context)支持,包括企业服务(如JNDI、JTA)和消息服务。它是构建Spring应用程序的核心模块之一。 -->
  9. <dependency>
  10. <groupId>org.springframework</groupId>
  11. <artifactId>spring-context</artifactId>
  12. <version>5.3.13</version>
  13. </dependency>
  14. <!-- spring-beans: 包含用于处理Bean的功能,包括Bean的定义、创建和管理。这个模块通常与spring-core一起使用。 -->
  15. <dependency>
  16. <groupId>org.springframework</groupId>
  17. <artifactId>spring-beans</artifactId>
  18. <version>5.3.31</version>
  19. </dependency>
  20. <!-- spring-aop: 提供了面向切面编程(AOP)的支持,允许您在应用程序中以声明性方式管理横切关注点。 -->
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-aop</artifactId>
  24. <version>5.3.29</version>
  25. </dependency>
  26. </dependencies>

定义 applicationContext.xml 文件,并添加扫描路径

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!-- 定义扫描路径 -->
  7. <context:component-scan base-package="cn.rollin.spring" />
  8. </beans>

添加一个测试类型UserService

在测试类 Main 中进行测试

  1. public class Main {
  2. public static void main(String[] args) {
  3. // 扫描路径
  4. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  5. // 获取bean
  6. UserService userService = (UserService) context.getBean("userService");
  7. userService.print();
  8. }
  9. }

可以看到 userService bean 已经初始化好了,并且执行了print 方法。


本文转载自: https://blog.csdn.net/luolin2611/article/details/134473715
版权归原作者 luolin2611 所有, 如有侵权,请联系我们删除。

“Idea 创建 Spring 项目(保姆级)”的评论:

还没有评论