不管学啥,搭建好环境,新建第一个工程都是非常重要的。

对于IDEA新建Spring项目,看了网上很多教程,发现都不是从新手第一次新建项目的角度来写的,很多都默认读者已经了解了某些背景知识和设置,因此新手第一次新建Spring项目的时候容易报各种错。

因此本文就从新手的角度来讲解一些怎么使用IDEA来新建第一个Spring项目。

软件版本

IDEA版本:2021.3 Ultimate

Spring版本:5.2.9

首先值得一说的就是IDEA的版本,我自己在查找教程的过程中,发现很多文章的IDEA版本或者页面选项完全不一样,比如有的教程新建项目的地方可以直接新建Spring项目,而我使用的版本就没有。因此为了使本篇教程更适合新手,我会使用更加普适的方法来建立Spring项目。

至于Spring版本,一般只要保持大版本一致即可。

Spring开发环境搭建,软件安装

开始学到Spring了,我默认大家已经安装好JDK和IDEA了。

如果没有的话可以查看教程:

Java JDK下载与安装教程

Java JDK环境变量配置

IDEA2021安装教程

确定好上面这些环境配置好之后,我们要开始安装Spring框架所需要的东西了。

Spring框架需要下载两个压缩包:

  • Apache Common Logging API

  • Spring

Common Logging 是使用 Spring 的必要组件。

Apache Common Logging API 下载地址:https://commons.apache.org/proper/commons-logging/download_logging.cgi

下载完成后,将压缩包解压到相应位置。例如 Windows 上的 C:\ commons-logging-1.2、Linux / Unix 上的 /usr/local/commons-logging-1.2 等。该文件包含以下 jar 文件和其它支持文档,目录结构如下。

Common Logging目录结构

Spring 下载地址:https://repo.spring.io/release/org/springframework/spring/

根据操作系统(Windows或Unix)下载相应的 Spring 压缩包。本教程使用版本为 spring-framework-5.2.3.RELEASE-dist.zip,该文件目录结构如下:

Spring目录结构

下面对上图所示的目录进行简单介绍,具体如表 1 所示。

名称作用
docs包含 Spring 的 API 文档和开发规范
libs包含开发需要的 jar 包和源码包
schema包含开发所需要的 schema 文件,在这些文件中定义了 Spring 相关配置文件的约束

在 libs 目录中,包含了 Spring 框架提供的所有 jar 文件,其中有 4 个 jar 文件是 Spring 框架的基础包,分别对应 Spring 容器的四个模块,具体如表 2 所示。

名称作用
spring-core-x.x.xx.RELEASE.jar包含 Spring 框架基本的核心工具类,Spring 其他组件都要用到这个包中的类,是其他组件的基本核心。
spring-beans-x.x.xx.RELEASE.jar所有应用都要用到的,它包含访问配置文件、创建和管理 Bean 以及进行 Inversion of Control(IoC)或者 Dependency Injection(DI)操作相关的所有类。
spring-context-x.x.xx.RELEASE.jarSpring 提供在基础 IoC 功能上的扩展服务,此外还提供许多企业级服务的支持,如邮件服务、任务调度、JNDI 定位、EJB 集成、远程访问、缓存以及各种视图层框架的封装等
spring-expression-x.x.xx.RELEASE.jar定义了 Spring 的表达式语言。 需要注意的是,在使用 Spring 开发时,除了 Spring 自带的 JAR 包以外,还需要一个第三方 JAR 包 commons.logging 处理日志信息

使用 Spring 框架时,只需将 Spring 的 4 个基础包以及 commons-logging-1.2.jar 包复制到项目的 lib 目录,并发布到类路径中即可。


使用两种方法来创建Spring项目

我在看教程的过程中,发现有的教程是使用自己导入Spring包的方式,有的是使用Maven的方式来导入Spring包的,因此为了文章的完备性,本文也会使用这两种方法来分别创建Spring项目。

对Maven不了解的,可看这篇博客:maven引入依赖包,import依赖包,编译运行maven项目.


1.1使用IDEA新建一个普通项目

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114114401505.png

新建好之后,项目目录结构如下:

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114114535142.png

1.2导入Spring包

因为我们的项目要使用这些包,因此要将其导入。

在项目名上右键,选择Open Module Settings

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114114848886.png

选择Libraries

image-20220114115001597

点击+号,新建Java

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114115101941.png

使用 Spring 框架时,只需将 Spring 的 4 个基础包以及 commons-logging-1.2.jar 包复制到项目的 lib 目录,并发布到类路径中即可。

如下图所示,将这5个包添加进来即可。

在这里插入图片描述

先点击Apply,再点击OK即可。

在这里插入图片描述

1.3新建两个java文件用来测试

新建两个文件MainApp.java和HelloWorld.java。文件内容如下

MainApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();
    }
}

HelloWorld.java

public class HelloWorld {
    private String message;
    public void setMessage(String message) {
        this.message = message;
    }
    public void getMessage() {
        System.out.println("message : " + message);
    }
}

此时,项目目录结构如下:

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114120045567.png

1.4创建Spring配置文件

为啥要创建这个配置文件,要理解这个问题,需要对Spring框架有一些了解。

我们需要创建一个配置文件 Beans.xml 。文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="HelloWorld">
        <property name="message" value="Hello World!" />
    </bean>

</beans>

此时项目的目录结构如下:

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114160352326.png

1.5 Project Structure设置

首先我们可以先看下这篇博客来了解一下IDEA中Project Structure设置:玩转IDEA项目结构Project Structure,打Jar包、模块/依赖管理全搞定

点击File-Project Structure,注意设置一下Source文件路径设置,以及Excluded的路径设置。

image-20220114161345001

在上面的页面,点击Facets

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114161653110.png

继续点击+号,新增一下 Beams.xml
https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114162312527.png

1.6注意看一下iml配置文件

我之前按照上面步骤配置的时候,发现会报错,后面发现是iml配置文件中

有关iml配置文件的了解可以看下面两篇博客:

IDEA中的.iml文件和.idea文件夹作用和意义

idea iml文件功能验证

我的iml配置文件中的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="Spring" name="Spring">
      <configuration>
        <fileset id="fileset" name="Spring Application Context" removed="false">
          <file>file://$MODULE_DIR$/Beans.xml</file>
        </fileset>
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" name="spring-beans-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-context-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-core-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-expression-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="commons-logging-1.2" level="project" />
  </component>
</module>

我们可以解析一下这个配置文件:

  <component name="FacetManager">
    <facet type="Spring" name="Spring">
      <configuration>
        <fileset id="fileset" name="Spring Application Context" removed="false">
          <file>file://$MODULE_DIR$/Beans.xml</file>
        </fileset>
      </configuration>
    </facet>
  </component>

这边的配置就是Spring框架的配置

file:// M O D U L E D I R MODULE_DIR MODULEDIR/Beans.xml,这边的设置就是Spring的配置文件的路径。

    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>

上面 设置是整个项目的文件结构,源文件的路径。

    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" name="spring-beans-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-context-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-core-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="spring-expression-5.2.9.RELEASE" level="project" />
    <orderEntry type="library" name="commons-logging-1.2" level="project" />

上面这些则是Spring框架的jar包。

一般如果我们配置正常的话,我们其实是可以不用管iml配置文件的。如果不能正常运行,那我们可能就要检查一下。

1.7看是否能否正常运行

在这里插入图片描述

如上图所示,则是运行成功了!

1.8可能会出现的问题

我在此过程中,出现过下面几种错误。

运行之后,报错信息如下:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342)
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310)
	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:257)
	at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:128)
	at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:94)
	at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
	at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:638)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
	at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
	at MainApp.main(MainApp.java:8)
Caused by: java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist
	at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:333)
	... 13 more

Process finished with exit code 1

另一种报错信息如下:

JAVA错误: 找不到或无法加载主类

上面这两种错误的主要原因就是Beams.xml和源文件的路径问题。

为了解决上面两个问题,我们只需要仔细查看1.5节和1.6节中的设置问题。


上面讲解了使用最通用的方法,下面我们继续讲解使用Maven来建立这个项目。

2.1新建一个Maven项目

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114171802265.png
此时项目的目录结构如下:

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114172606330.png

2.2使用Maven配置文件导入Spring包

只需要在pom.xml中添加依赖即可,我们需要在pom.xml中添加如下内容:

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <!--https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <!--https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

不同版本的jar包可以在这个网址查询:https://mvnrepository.com/search?q=

2.3新建两个java文件用来测试

这两个文件和第一种方法中的文件内容一样。创建完之后,项目目录结构如下:

在这里插入图片描述

2.4新建Spring配置文件 Beans.xml

Beans.xml的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="HelloWorld">
        <property name="message" value="Hello World!" />
    </bean>
</beans>

2.5 Project Structure设置

这个和上面一样,在Facets中新建一个Spring,并且添加一下Spring配置文件Beans.xml。

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114190922433.png

image-20220114191003405

2.6 看看是否能正常运行

如果正常运行,应该如下图所示

https://raw.githubusercontent.com/xkyvvv/blogpic2/main/img/image-20220114191349740.png


总结

其实可以发现,上面两种方法的区别主要是导入Spring框架包的方法不同,其他步骤基本相同。

其实IDEA还有一种方法可以导入Spring框架包。

新建一个项目之后,我们可以在项目名上右键,选择Add FrameWork Support,在其中选择Spring,也可以将Spring框架的所有Jar包下载下来。

image-20220114192826266

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐