Spring3实例入门-Hello World

每次看到hello world,都有一种说不出的赶脚,想起了一个程序员,退休后写毛笔字,取笔研磨铺纸,大笔一挥,写下了“hello world”。

1.使用Maven生成项目结构

mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=Spring3Example 
    -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

 2.转换成Eclipse项目

mvn eclipse:eclipse

 3.添加Spring3.0 依赖

在pom.xml文件里添加Spring 3.0 依赖,然后依赖会从Maven中央仓库自动下载

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong.core</groupId>
    <artifactId>Spring3Example</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Spring3Example</name>
    <url>http://maven.apache.org</url>

&lt;properties&gt;
    &lt;spring.version&gt;3.0.5.RELEASE&lt;/spring.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;

    &lt;!-- Spring 3 dependencies --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
        &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
        &lt;version&gt;${spring.version}&lt;/version&gt;
    &lt;/dependency&gt;

&lt;/dependencies&gt;

</project>

 4.Spring bean

写个简单的bean

package com.mkyong.core;

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

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

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

}

 5.Spring bean配置文件

创建一个配置文件,在里面声明所有可用的Spring 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-3.0.xsd">

&lt;bean id="helloBean" class="com.mkyong.core.HelloWorld"&gt;
    &lt;property name="name" value="Mkyong" /&gt;
&lt;/bean&gt;

</beans>

 6.最终的目录结构

Spring3-hello-world-example

 

7.运行

package com.mkyong.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(
                "SpringBeans.xml");

        HelloWorld obj = (HelloWorld) context.getBean("helloBean");
        obj.printHello();
    }
}

 8.输出

Spring 3 : Hello ! Mkyong

 9.Demo下载

Spring3-hello-world-example.zip 

comments powered by Disqus