HelloWorld of Spring
这里举一个向某 POJO 的一个属性注入一个字符串值的例子,体现了 DI(Dependency Injection)的思想。
本例的代码实例参 http://git.oschina.net/iridiumcao/iridiumonline/tree/master/hellospring
Create Project
首先新建一个 java project,然后转化为 maven 工程,在 <dependencies>
中添加 Spring 的相关配置如下:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
注意:添加后,因为共匪的网络封锁,可能出现问题:
这时可以去官网下载:http://maven.springframework.org/release/org/springframework/spring/4.0.6.RELEASE/
下载好后解压,然后手工将相关的 jar 包,放置当 maven repository 对应的目录中。
如果网络情况不是太坏,通过 Eclipse 的 maven 菜单也许可以操作成功:
POJO - HelloWorld
public class HelloWorld {
private String message ;
public void getMessage() {
System.out.println("Your message: " + this.message );
}
public void setMessage(String message) {
this.message = message;
}
}
Configuration - beans
<? 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="HelloWorld">
< property name="message" value="Hello World!" />
</bean>
</beans>
这里为 HelloWorld 类的 message 属性注入字符串值"Hello World!". 在生产应用中,还可以注入别的类的实例,这里也可以看成是注入了 String 类的实例。
MainApp
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
String beanFilePath = "beans.xml" ; // 此处勿用绝对路径
ApplicationContext context = new ClassPathXmlApplicationContext(beanFilePath);
HelloWorld obj = context.getBean("helloWorld", HelloWorld.class);
System.out.println(obj.getMessage());
}
}
在 MainApp 中可以看出,创建 HelloWorld 实例,没有通过传统的方式去 new HelloWorld(),而是通过读入 Spring 配置创建的,因为在 beans.xml 中,给 HelloWorld.message 已设置值,在创建 HelloWorld 实例时,这个值会按照配置的设定注入新建的示例中去。故,上面的代码执行后,可以看到输出:
Your message: Hello World!
参考:
官网首页: http://projects.spring.io/spring-framework/
在线文档: http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/
在线 API: http://docs.spring.io/spring/docs/4.0.6.RELEASE/javadoc-api/