Spring IDE

Posted on 2009-11-09 12:37 shoppingbill 阅读(363) 评论(0)  编辑  收藏 所属分类: Spring
 

Spring IDE是一个Eclipse插件帮助开发Spring 应用.首先我们先来看看怎么样安装Spring IDE,然后用Spring IDE创建我们一个Spring项目.我用的是Eclipse 3.4.1版本来演示它.
安装Spring IDE,Help -> Software Updates.


点击'Add Site'按钮,键入'http://springide.org/updatesite'


选择所有Spring IDE features 点击Install.


安装结束之后,让我们用Spring IDE创建我们的hello world例子。
首先创建Spring项目, File ->Project.



选择Spring Project点击Next.


输入项目名点击Finish.



右上角"S"表示它是一个Spring项目.


右击src创建新的包"com.vaannila".创建HelloWorld

01.package com.vaannila;
02. 
03.public class HelloWorld {
04. 
05.private String message;
06. 
07.public void setMessage(String message) {
08.this.message = message;
09.}
10. 
11.public void display()
12.{
13.System.out.println(message);
14.}
15.}


HelloWorld类有一个message属性,用setMessage()方法赋值.这种叫做setter注入.代替了用编码。我们通过外部的配置文件注入它。用到的设计模式叫做 Dependency Injection 模式。下个例子我们一起来理解它。HelloWorld类有个display()方法显示信息。
现在我们创建HelloWorld bean 类。下一步是把它添加到bean配置文件中。bean的配置文件在通过Spring Ioc容器来配置。创建一个新的bean配置文件。右击src文件夹选择New -> Spring Bean Configuration File.

输入bean的名字点击Next.

选择beans option点击Finish.

现在Spring配置文件已经创建。添加以下代码创建HelloWorld bean类。

01.<?xml version="1.0" encoding="UTF-8"?>
02.<beans xmlns="http://www.springframework.org/schema/beans"
03.xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04.xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
05. 
06.<bean id="helloWorld" class="com.vaannila.HelloWorld">
07.<property name="message" value="Hello World!"></property>
08.</bean>
09. 
10.</beans>


bean
id属性是给bean一个逻辑命名。类的属性指定全局的bean类名。bean元素里面的<property>元素是用来给bean赋值的。这里我给“Hello World如果你想显示不同的信息,值需要在bean的配置文件里改变bean的值就好了。这个是Dependency Injection 设计模式的一个最大的好处。让你的代码更加松散耦合。

显示信息,创建如下HelloWorldApp

01.package com.vaannila;
02. 
03.import org.springframework.context.ApplicationContext;
04.import org.springframework.context.support. ClassPathXmlApplicationContext;
05. 
06.public class HelloWorldApp {
07. 
08.public static void main(String[] args) {
09.ApplicationContext context = newClassPathXmlApplicationContext("beans.xml");
10.HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
11.helloWorld.display();
12.}
13. 
14.}

首先初始化Spring Ioc容器(配置文件bean.xml)。我们用getBean()方法从application context获取HelloWorld bean调用这个display()方法在控制台上显示信息。

如图最终的hello world例子目录结构



添加如下jar文件到classpath

1.antlr-runtime-3.0
2.commons-logging-1.0.4
3.org.springframework.asm-3.0.0.M3
4.org.springframework.beans-3.0.0.M3
5.org.springframework.context-3.0.0.M3
6.org.springframework.context.support-3.0.0.M3
7.org.springframework.core-3.0.0.M3
8.org.springframework.expression-3.0.0.M3

 

To execute the example run the HelloWorldApp file. The "Hello World!" message gets printed on the console.
运行这个例子HelloWorldApp文件。“Hello World会显示在控制台上。

Source :Download

Source + Lib :Download




只有注册用户登录后才能发表评论。


网站导航:
 

posts - 6, comments - 0, trackbacks - 0, articles - 0

Copyright © shoppingbill