spring入例(1)

 1 新建一個項目

file----->new ----->project  在出現的對話框中選擇 myeclipse 下的 webproject 如圖
 
project name 寫入mySpring1 其他的選項默認 下面點finish完成

2 加入spring 包

 在myspring1 項目上點右鍵 選myeclipse ---> add spring capabities

3 加入log4j 包

菜單---project --properties-----java build path 點libraries 選項卡 再

選 add external jars 加入 log4j 的jar 包 (可從網上下)

 

4 新建 Action接口文件

右鍵點src ----new ----interface (包名net.xiaxin.spring.qs)

Action.java代碼

package net.xiaxin.spring.qs;

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

}
5 建立Action接口的兩個實現UpperAction、LowerAction

LowerAction.java

package net.xiaxin.spring.qs;

public class LowerAction 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).toLowerCase();
    }
  }

/////
UpperAction.java

package net.xiaxin.spring.qs;

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

6  新建log4j.properties配置文件,
內容如下:

log4j.rootLogger=DEBUG, stdout
 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n

7  Spring配置文件(bean.xml)

在myspring 上右擊 --->new--->file  文件名 bean.xml

bean.xml 內容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
     <description>Spring Quick Start</description>
     <bean id="TheAction"
 class="net.xiaxin.spring.qs.UpperAction">
    <property name="message">
<value>HeLLo</value>
</property>
  </bean> 
 <bean id="action2" class="net.xiaxin.spring.qs.LowerAction">
<property name="message">
<value>HeLLo</value>
</property>
  </bean>
</beans>


8  建立測試文件SimpleTest.java

package test;

import net.xiaxin.spring.qs.Action;

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

public class SimpleTest {
 public static void main(String args[])
 {
  SimpleTest test=new SimpleTest();
  test.testQuickStart();
  
 }
 public void testQuickStart() {
  
     ApplicationContext ctx=new 
 FileSystemXmlApplicationContext("bean.xml");
    
     Action action = (Action) ctx.getBean("TheAction");
    
     System.out.println(action.execute("Rod Johnson"));
     action = (Action) ctx.getBean("action2");
     System.out.println(action.execute("jecKj"));
 
  }

}

9 把SimpleTeat.java 設置成主類就可以運行了可以運行了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章