用IDEA写第一个Spring程序 HelloWorld
用IDEA写第一个Spring程序 HelloWorld
环境 Orcal JDK:1.8.0_341 maven:3.9.3 Spring:5.3.10 IDEA:2023.1.2
1. 安装JDK和IDEA
2. 安装maven并配置环境变量、换源
3. IDEA中maven属性配置,主要是版本和settings文件及仓库地址
4. 新建HelloWorld项目
4.1 File-New-Project-MavenArchetype
改一下项目名取名为MyTest,Archetype选择quickstrat ,然后点击create。
4.2 poe.xml修改
在project中加入包依赖,点击刷新自动获取springframwork和commons-logging。
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.10</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> </dependencies>
4.3 目录结构如下
-
注意在IDEA中src/main下面的java文件夹不是一个包,不要把包名加上main和java,编译后的target也不带main和java文件夹。
1)在src的org.example包中创建HelloWorld和Main两个类,源码如下: HelloWorld.java
package org.example; public class HelloWorld { private String name; public HelloWorld() { System.out.println("HelloWorlds Constructing....... "); } public void setName(String name){ System.out.println("setName: " + name); this.name = name; } public void hello(){ System.out.println("hello: " + name); } }
2)在main中新建一个resources文件夹,文件夹中新建一个Spring Config,名称为ApplicationContext.xml,源码如下: ApplicationContext.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="org.example.HelloWorld"> <property name="name" value="Spring!!!!!"></property> //这里的意思是调用setName函数把HelloWorld类中的name字段设置为"Spring!!!!!"。 </bean> </beans>
3)最后,Main类的源码如下: Main.java
package org.example; import org.example.HelloWorld; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args){ ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml"); HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloworld"); helloWorld.hello(); } }
4.4 对Main.java编译运行
得到结果如下:
至此,一个Spring的Hello World测试代码编写完毕,该项目主要用来测试Spring安装是否成功。
上一篇:
通过多线程提高代码的执行效率例子