秦悦明的运维笔记

spring-helloworld

1.创建一个java项目

最好是maven项目,可以自己下载包,比较方便。

2.添加spring库

1
2
3
4
5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>

3.创建源文件

HelloWord.java
一个普通的class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.tutorialspoint;
/**
* Created by gqdw on 13/10/2016.
*/
public class HelloWorld {
private String message;
public void setMessage(String m){
message = m;
}
public void getMessage(){
System.out.println("your Message : " + message);
}
}

MainApp.java
MainApp通过spring bean来获取对接,然后调用他的方法,bean通过xml文件来配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.tutorialspoint;
/**
* Created by gqdw on 13/10/2016.
*/
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();
}
}

ClassPathXmlApplicationContext来获取context,然后用context的getBean方法来获取HelloWorld对象。

Beans.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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-3.0.xsd">
<bean id="HelloWorld" class="com.tutorialspoint.HelloWorld">
<property name="message" value="Hello World! aca"/>
</bean>
</beans>

Bean文件配置了一个id,class,相当于new了一个HelloWorld对象。value给message,

4.运行程序

程序正常运行就能打印出

1
Your Message : Hello World! aca

简单的helloworld程序,演示了spring bean的装配。