用 MyEclipse 开发 Spring 入门操作

时间:2021-04-20 13:19:20
何为Spring
Spring框架是一个轻量级的控制反转(IOC)技术和面向切面编程(AOP)技术的容器框架,利用Spring框架可以实现对象的生命周期管理和分离应用系统中的业务逻辑组件和通用的技术服务组件。

接下来开始我们的第一个Spring程序

1. 首先新建 Java 项目 Test. 这个过程无需赘述了, 建议建项目的时候将 src 目录和 bin(或者classes)目录分开, 另外提示你切换透视图的时候一定要切换过去到 Java 透视图, 此时默认会在 Package Explorer 中选中刚才已经建好的 Java Project.

2. 单击一下新建的Test 项目来, 接着点击菜单项 MyEclipse -> Add Spring Capabilities..., 接着会弹出对话框 Add Spring Capabilities 提示你设置当前项目的 Spring 属性.
对话框的第一页可以选择全部的 Spring 框架, 不过我们的例子只需要选中Spring 2.0 Core Libraries 就可以了. 点击 "Next" 继续.
第二页是 Add Spring bean configuration file. 保持默认值不变. 接着点击 Finish.

3. Spring 的开发没法自动生成 Bean, 需要我们手动添加. 分别复制下面的三段代码, 然后在 MyEclipse src 目录上选择菜单项 Paste 就可以生成 Java 类文件了.

因为在使用中由于自动识别,会出现代码混乱错误,故将下面三个代码标注

这是第一段代码

public interface Action { 
  
  public String execute(String str); 
 
}

这是第二段

public class UpperAction implements Action { 
  
  private String message; 
  
  public String getMessage() { 
   return message; 
  } 
 
  public void setMessage(String string) { 
    message = string; 
  } 
 
  public String execute(String str) { 
   return (getMessage() + str).toUpperCase(); 
  } 
}

这是第三段代码

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

public class TestAction {

public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext(
    "applicationContext.xml");
  Action bean = (Action) ctx.getBean("theAction");
  System.out.println(bean.execute("Rod"));
 }
}

4. 双击左侧在第2步生成的 applicationContext.xml, 然后选择菜单项 Window -> Show View -> Other..., 在弹出的对话框中选择 MyEclipse Enterprise Workbench 节点下的 Spring Beans 子节点打开视图 Spring Beans. 此视图讲出现在主界面的右下侧.

5. 展开此视图中的 Test, 并选中 applicationContext.xml , 在此点击右键并选择弹出菜单项中的 New Bean 来打开 Create a new Spring bean 对话框, 并按照下图输入对应的内容.
Bean Id: [theAction]
Bean class: [UpperAction]
接下来请单击一下 Tab 面板 Properties 并点击其中的 Add 按钮, 在接下来弹出的 Property Wizard 对话框中按照下图输入/选择内容:
Name: [message]
Spring type: [value]
Type: [java.lang.String]
Value:[Hello_]
接着打开 applicationContext.xml 可以看到如下内容:
 <bean id="theAction" class="UpperAction" abstract="false"
  lazy-init="default" autowire="default" dependency-check="default">
  <property name="message">
   <value type="java.lang.String">Hello_</value>
  </property>
 </bean></beans>
然后双击 建立的Test项目,打开Test/src/TestAction.java 打开源代码, 然后运行TestAction.java, 如果没有错误, 则 Hello Spring 运行成功了:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
HELLO_ROD