码迷,mamicode.com
首页 > 编程语言 > 详细

[译]5-Spring Hello World

时间:2015-05-04 21:39:49      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

本文采用step-by-step方式进行讲解,以后的文章中就略写了。

新建Java项目

打开Eclipse。File->New->Java Project

技术分享

填写项目基本信息,这里我们只需要提供项目名称即可

技术分享

点击Finish,应该出现类似如下界面

技术分享

 

添加依赖jar包

在HelloSpring项目上右击,按照如下图操作

技术分享

在弹出的窗口中的Libraries tab页选择Add External Jars

技术分享

添加如下jar包:

技术分享

创建源文件

创建com.tutorialspoint包,如下:

技术分享

在弹出的窗口中填入包名

技术分享

点击Finish。

 

在包com.tutorialspoint中创建HelloWorld.java。在包上右击,按如下操作

技术分享

在弹出的窗口中写入类名

技术分享

在HelloWorld.java类文件中输入如下代码:

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

 

以同样的方式在包com.tutorialspoint中创建MainApp.java,并输入如下代码:

package com.tutorialspoint;

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

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();
   }
}

 

在MainApp.java中我们需要注意如下两点

  • 第一步我们首先创建了Spring容器,使用ClassPathXmlApplicationContext类的实例来创建Spring容器。
    在创建spring容器的时候框架会去类路径下寻找Beans.xml,最后根据Beans.xml的内容创建和初始化容器
    中的bean实例。
  • 第二步我们使用容器的getBean方法来得到容器中的一个实例。

创建Bean的配置文件

技术分享

并在新建的文件中输入如下内容:

<?xml version="1.0" encoding="UTF-8"?>

<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="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

 运行

技术分享

[译]5-Spring Hello World

标签:

原文地址:http://www.cnblogs.com/sysman/p/4477153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!