1. 程式人生 > >Spring(4)--- hello world例項

Spring(4)--- hello world例項

Spring hello world例項

 

本教程介紹如何在Spring4 中建立一個簡單的 Hello World 例子。

在這篇文章中使用的技術或工具:

  1. Spring 4.1
  2. Eclipse 10
  3. JDK 1.8

專案文件結構:建立MAVEN 專案

 

 

 

pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.javass.spring.chapter2</groupId>
  <artifactId>HelloSpring1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <dependencies>
 
        <!-- Spring Core -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
         
        <!-- Spring Context -->
        <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
             
    </dependencies>
</project>

Beans 檔案

<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.xsd">
  
    <bean id="helloBean" class="com.zyzx.core.HelloWorld">
        <property name="name" value="zyzx" />
    </bean>
  
</beans>

執行檔案

package com.zyzx.core;

/**
 * Spring bean
 * 
 */
public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void printHello() {
        System.out.println("Spring 4 : Hello ! " + name);
    }
}

package com.zyzx.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "beans.xml"); 
        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}

輸出結果:

Spring 4 : Hello ! zyzx