spring第一个应用 HelloWorld实例
一、HelloWorld
1.HelloWord.java
package com.forcoldplay.spring.test;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
System.out.println("message : " + message);
return message;
}
}
2.MainApp.java
package com.forcoldplay.spring.test;
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");
//1.使用框架 API ClassPathXmlApplicationContext() 来创建应用程序的上下文。
// 这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理创建并初始化所有的对象,即在配置文件中提到的 beans。
HelloWorld obj = context.getBean("helloWorld",HelloWorld.class);
//2.用已创建的上下文的 getBean() 方法来获得所需的 bean。
// 这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象。
obj.getMessage();
// 一旦有了对象,你就可以使用这个对象调用任何类的方法。
}
}
3.创建 bean 的配置文件
<?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-3.0.xsd">
<bean id="helloWorld" class="com.forcoldplay.spring.test.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
</beans>
4.编译运行。
message : Hello World!