01 Spring HelloWorld
环境:
IDEA 2019.2
jdk 1.8及以上
Maven 3以上
- 创建Maven的Web项目,然后导入依赖:
1 |
|
在src目录下新建java文件夹,作为java代码的存放文件夹,新建Spring xml描述文件,名为
applicationContext.xml
在src目录下新建包Hello,在包下新建类HelloWorld.java
HelloWorld.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package hello;/*
* @Author Sheng WenZeng
* @Date 2019/8/4 15:22
* @Version 1.0
*/
/**
* @author Sheng Wenzeng
* @ClassName HelloWorld
* @Description TODO
* @Date 2019/8/4 15:22
* @Version 1.0
*/
public class HelloWorld {
private String name_1;
private String name_2;
void hello() {
System.out.println(name_1 + name_2);
}
public void setName_1(String name_1) {
this.name_1 = name_1;
}
public void setName_2(String name_2) {
this.name_2 = name_2;
}
}在applicationContext.xml中写入bean
applicationContext.xml:
1
2
3
4
5
6
7
8
9
10
11
<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-->
<bean id="helloWord" class="hello.HelloWorld">
<property name="name_1" value="Hello"/>
<property name="name_2" value="World"/>
</bean>
</beans>新建Hello类
Hello.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package hello;
/*
* @Author Sheng WenZeng
* @Date 2019/8/4 15:24
* @Version 1.0
*/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Sheng Wenzeng
* @ClassName Hello
* @Description TODO
* @Date 2019/8/4 15:24
* @Version 1.0
*/
public class Hello {
public static void main(String[] args) {
//这一步会自动执行HelloWorld的构造方法,并将name值通过其中的set方法赋给name
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWord");
helloWorld.hello();
}
}运行Hello.java
1
2
3
4"C:\Program Files\Java\jdk1.8.0_211\bin\java.exe" ...
HelloWorld
Process finished with exit code 0