[Spring in Action] 2. Hello Spring
这一篇就亲自实践一个简单的Spring应用。依旧类似人见人爱的“Hello World”, 不过稍微有些改动,是“Hello Spring”.
HelloWorld.java
package hello.spring; public class HelloWorld { private String words; public String getHello() { return words; } public void setHello(String words) { this.words = words; } public void show(){ System.out.println("Message: "+this.words); } }
Spring bean配置文件:myspring.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-2.5.xsd" <bean id="myBean" class="hello.spring.HelloWorld"> <property name="hello"> <value>Hello Spring!</value> </property> </bean> </beans>
HelloSpring.java
package hello.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class HelloSpring { public static void main(String[] args){ ApplicationContext ctx = new FileSystemXmlApplicationContext("src/myspring.xml"); HelloWorld hw = (HelloWorld)ctx.getBean("myBean"); hw.show(); } }