1. 程式人生 > >Spring環境搭建和示例工程

Spring環境搭建和示例工程

/**

 * spring官網:https://spring.io/

下載地址http://projects.spring.io/spring-framework/

Spring Framework下的Reference

2.3. Usage scenarios

點選Distribution Zip Files

Distribution Zip Files

真實下載地址 http://repo.spring.io/release/org/springframework/spring

點選一個版本

然後點選最上層的第一個:spring-framework-4.3.3.RELEASE-dist.zip 解壓

 * 第一步:新建一個普通java工程new-other-java Project

第二步:建立lib資料夾,引入spring-framework的jar檔案全部拷貝到工程中

javadoc和sources 結尾的不用拷貝

最主要的有:spring-aop、spring-beans、spring-context、spring-core

第三步:新增到buildPath:右鍵點選工程名稱-Properties-Java Build Path-Add JARs… 

下載Apache Commons Logging

http://commons.apache.org/proper/commons-

logging/download_logging.cgi

commons-logging-1.2.jar也同上新增進去/

 */

IHelloMessage.java介面檔案:

package com.jike.spring.chapter01;

publicinterfaceIHelloMessage{

publicStringsayHello();

}


HelloChina.java檔案:

package com.jike.spring.chapter01;

publicclassHelloChinaimplementsIHelloMessage{

@Override

publicStringsayHello(){

// TODO Auto-generated method stub

return"大家好!";

}

}


HelloWorld.java檔案:

package com.jike.spring.chapter01;

publicclassHelloWorldimplementsIHelloMessage{

@Override

publicStringsayHello(){

// TODO Auto-generated method stub

return"Hello World!";

}

}


Person.java檔案:

package com.jike.spring.chapter01;

publicclassPerson{

private IHelloMessage helloMessage;

publicIHelloMessagegetHelloMessage(){

return helloMessage;

}

publicvoidsetHelloMessage(IHelloMessagehelloMessage){

this.helloMessage= helloMessage;

}

publicStringsayHello(){

return this.helloMessage.sayHello();

}

}


helloMessage.xml檔案:

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEbeansPUBLIC"-//SPRING/DTD BEAN/EN"

"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<beanid="helloWorld"class="com.jike.spring.chapter01.HelloWorld"></bean>

<beanid="helloChina"class="com.jike.spring.chapter01.HelloChina"></bean>

<beanid="person"class="com.jike.spring.chapter01.Person">

    <propertyname="helloMessage"ref="helloChina"/>

</bean>

</beans>


Main.java檔案:

package com.jike.spring.chapter01;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

import org.springframework.core.io.Resource;

publicclassMain{

//2.Spring 入門示例----03建立示例工程

publicstaticvoidmain(String[]args){

//載入配置檔案 以及啟動IOC容器  呼叫人物類 向用戶輸出問候資訊

Resource r = new FileSystemResource("helloMessage.xml");

BeanFactory f=newXmlBeanFactory(r);

Person person=(Person)f.getBean("person");

String s = person.sayHello();

System.out.print("The person is currently saying:"+ s);

}

}

//Main.java右鍵RunAs--java Application