Spring3系列1-HelloWord例子

一、      环境

spring-framework-3.2.4.RELEASE

jdk1.7.0_11

Maven3.0.5

eclipse-jee-juno-SR2-win32

二、      用Maven创建项目

mvn archetype:generate -DgroupId= com.lei.demo -DartifactId=Spring3-Example

       -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

然后转换成Eclipse项目:mvn eclipse:eclipse

或者直接在Eclipse中创建maven-archetype-quickstart项目。

三、      编辑pom.xml,加入spring3依赖

<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>com.lei.demo</groupId>
  <artifactId>spring3-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring3-Example</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
      <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- Spring3配置 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.4.RELEASE</version>
    </dependency>
  </dependencies>
</project>

四、      创建一个Spring Bean

一个简单的spring  bean如下

package com.lei.demo.helloworld;

public class HelloWorld {

    private String name;
     
    public void setName(String name) {
        this.name = name;
    }
 
    public void printHello() {
        System.out.println("第一个Spring 3 : Hello ! " + name);
    }
}

五、      创建Spring Bean的配置文件

创建文件SpringBeans.xml,配置bean如下。文件位于src/main/resources下

<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.lei.demo.helloworld.HelloWorld">
        <property name="name" value="leiOOlei" />
    </bean>
 
</beans>

六、      创建测试App

package com.lei.demo.helloworld;

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

public class App {
    
    private static ApplicationContext context;

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

}

七、      目录结构

 

 

八、      运行结果

 

 

转自:http://www.cnblogs.com/leiOOlei/p/3441419.html

posted @ 2016-01-21 16:06  门罗的魔术师  阅读(117)  评论(0编辑  收藏  举报