版权声明:本文为博主原创文章,欢迎转载,转载请注明出处 https://blog.csdn.net/qq_40147863/article/details/85629271
Spring 笔记 -03- Spring入门实例- Hello Word!
步骤:
(1)新建项目,参考 Spring 笔记 -01- Junit 单元测试 中的步骤一
(2)在 main/java 目录下,新建包 com.spring
(3)在上述包下,新建 HelloWorld.java,编写代码:
package com.spring;
public class HelloWorld {
public void sayHello (String str){
System.out.println("HelloWorld " + str);
}
}
(4)使用 maven 配置 Spring -core 包和 Context 包
打开:
-
https://mvnrepository.com/artifact/org.springframework/spring-core
-
https://mvnrepository.com/artifact/org.springframework/spring-context
粘贴到 pom.xml 文件中:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xpwi</groupId>
<artifactId>firstMaven</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
</project>
(5)在 resource 中新建一个 SpringConfig 文件,命名为 bean.xml :
(6)bean.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="hello" class="com.spring.HelloWorld"></bean>
</beans>
(7)在 Test/java 目录中,新建测试类 TestSpring.java 文件,内容为:
import com.spring.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void testSpring(){
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
HelloWorld hw = (HelloWorld) ac.getBean("hello");
String name = JOptionPane.showInputDialog("请输入一个名字");
hw.sayHello(name);
}
}
运行程序!
大家可能遇到错误,应该就是使用 JUnit 的问题,请参考:
Spring 笔记 -01- Junit 单元测试