Spring In Action (1) -- HelloWorld

来源:互联网 发布:知敬畏明底线 编辑:程序博客网 时间:2024/04/25 21:05

Spring版Hello World示例的第一个类是一个服务类,它的作用是打印出那句声名狼藉的问候。如下程序清单显示了GreetingService.java接口,它定义了我们的服务类需要提供的服务。GreetingServiceImpl.java是接口的实现。

 

 

 

  1. package com.springinaction.chapter01.hello;
  2. public interface GreetingService {
  3.     public void sayGreeting();
  4. }
  5. package com.springinaction.chapter01.hello;
  6. public class GreetingServiceImpl implements GreetingService {
  7.     private String greeting;
  8.     
  9.     public void sayGreeting() {
  10.         System.out.println(this.greeting);
  11.     }
  12.     public GreetingServiceImpl(String greeting) {
  13.         super();
  14.         this.greeting = greeting;
  15.     }
  16.     public GreetingServiceImpl() {
  17.         super();
  18.     }
  19.     public String getGreeting() {
  20.         return greeting;
  21.     }
  22.     public void setGreeting(String greeting) {
  23.         this.greeting = greeting;
  24.     }
  25. }

Spring配置文件hello.xml告诉容器如何配置服务

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
  3. <beans>
  4.     <bean id="greetingService" class="com.springinaction.chapter01.hello.GreetingServiceImpl">
  5.         <property name="greeting">
  6.             <value>I Love Aneya!</value>
  7.         </property>
  8.     </bean>
  9. </beans>

剩下的任务就是建立一个类来载入Spring容器并且利用它来获取服务:

 

 

 

  1. package com.springinaction.chapter01.hello;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.FileSystemXmlApplicationContext;
  4. public class HelloApp {
  5.     /**
  6.      * @param args
  7.      */
  8.     public static void main(String[] args) {
  9.         ApplicationContext applicationContext = new FileSystemXmlApplicationContext("hello.xml");
  10.         GreetingServiceImpl greetingServiceImpl = (GreetingServiceImpl)applicationContext.getBean("greetingService");
  11.         greetingServiceImpl.sayGreeting();
  12.     }
  13. }

最后,需要指出的是,为了让这段代码能够顺利执行,有两个包是必须引用的:spring.jar和commons-logging-1.1.1.jar