本文研究的主要是spring學習之創建項目Hello Spring實例代碼,具體如下。
1、eclipse創建java project項目HelloSpring
2、創建lib目錄,加入spring必須的5個jar包
3、選中5個文件,右鍵-> Build Path -> add to build path
1、創建包io.spring.beans,並編寫HelloWorld.java
package io.spring.beans;/** * @author 胖胖のALEX E-mail:[email protected] * @version 1.0 */public class HelloWorld {private String name;public void setName(String name) {this.name = name;}public void hello() {System.out.println("hello " + name);}}
2、src右鍵-> 創建spring bean configuration文件applicationContext.xml
<?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.xsd"> <!-- 配置bean --> <bean id="helloWorld"> <property name="name" value="大紅"></property> </bean> </beans>
3、編寫Main.java
package io.spring.beans;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author 胖胖のALEX E-mail:[email protected] * @version 1.0 */public class Main {public static void main(String[] args) {//1、創建Spring的IOC容器對象ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//2、從IOC容器中獲取Bean實例HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//3、調用hello方法helloWorld.hello();}}
輸出結果
當console內打印出紅色spring日誌,表示spring應用成功
以上就是本文關於spring學習之創建項目Hello Spring實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!