HelloSpring

HelloSpring

任何語言都是從Hello開始,那麼我們從HelloSpring開始認識Spring

代碼

Hello Spring 直接從代碼對Spring有一個整體的瞭解。

HelloWorld.java

package com.soygrow.HelloSpring;

public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("Your Message : " + message);
    }
}

MainApp.java

package com.soygrow.HelloSpring;

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

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("HelloSpringBeans.xml");

        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
        helloWorld.getMessage();
    }
}

HelloSpringBeans.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 id="helloWorld" class="com.soygrow.HelloSpring.HelloWorld">
        <property name="message" value="Hello Soygrow!"/>
    </bean>
</beans>

代碼分析

關於MainApp有一下兩點需要注意的:
- 第一步我們使用框架的API ClassPathXmlApplicationContext()來創建應用程序的上下文。這個API加載beans的配置文件並最終基於所提供的API,它處理創建並初始化所有的對象,即將Beans.xml中的Bean初始化並生成對象。
- 第二步使用已創建的上下文的getBean()方法獲得所需要的bean,這個方法使用bean的ID返回一個最終可以轉換爲實際對象的通用對象。一旦有了對象就可以調用任何屬於它的方法。

Beans.xml用於給不同的bean分配一個唯一的ID,並且控制不同值的對象的創建,而不影響Spring的任何源文件。

遇到的問題

網上的教程,在自己的手裏都會遇到各種各樣的問題,所以這裏記錄自己遇到的問題。

  • 找不到Beans.xml

使用IntelliJ IDEA創建Spring時,不會出現WEB-INF目錄,如果自己創建該目錄可能會提示下面信息,表示找不到xml文件。

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [Beans.xml]; 
nested exception is java.io.FileNotFoundException: class path resource [Beans.xml] cannot be opened because it does not exist

解決方法:
IntelliJ IDEA中 選中xml所在的目錄右鍵->Make Directory as->Reource roots

專欄地址:http://blog.csdn.net/column/details/19452.html

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