欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Spring 3 的 Hello world 示例,springhello,同样是 Hello wo

来源: javaer 分享于  点击 41968 次 点评:105

Spring 3 的 Hello world 示例,springhello,同样是 Hello wo


同样是 Hello world , Spring 的做法那是相当复杂啊,本代码使用的环境Spring 3.0.5.RELEASEMaven3.0.3Eclipse 3.6JDK 1.6.0.13

使用 Maven 创建项目结构

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

转化成 Eclipse 项目

mvn eclipse:eclipse

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/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>    <properties>        <spring.version>3.0.5.RELEASE</spring.version>    </properties>    <dependencies>        <!-- Spring 3 dependencies -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-core</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${spring.version}</version>        </dependency>    </dependencies></project>

一个简单的 Spring 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);    }}

SpringBeans.xml

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

项目结构预览

imgs/asCode/15080036_CHxK.png

运行

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();    }}

输出结果

Spring 3 : Hello ! Mkyong
相关栏目:

用户点评