第一個Spring Demo

一、Main文件

package com.pb;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**   
*    
* 項目名稱:PB_SpringDemo   
* 類名稱:HellpSpring   
* 類描述:   第一個Spring項目
* 建立人:Administrator   
* 建立時間:2019年7月6日 上午7:23:43   
* 修改人:Administrator   
* 修改時間:2019年7月6日 上午7:23:43   
* 修改備註:   
* @version    
*    
*/
public class HelloSpring {

    //須要注入的屬性,這個名字跟Bean裏的沒有任何關係
    private String input_str=null;
    
    /*
     * 注意點1:依賴注入的是靠 get和set方法的名字來確認的,好比本例子中是getMyStr和setMyStr,那麼Bean裏的屬性名字就必須配置爲myStr,不然出錯
     * 注意點2:Bean的屬性名字必須是首字母小寫,如本例中是 myStr,不能寫成MyStr,不然報[Invalid property 'MyStr' of bean class [com.pb.HelloSpring]: No property 'MyStr' found]
     * 注意點3:get和set方法必須對應起來,不能是這樣 getMYStr和setMyStr,大小寫不一致也會出錯
     */
    public String getMyStr() {
        return this.input_str;
    }
    public void setMyStr(String strParam) {
        this.input_str=strParam;
    }
    
    public void Print()
    {
        System.out.println("Hello,"+this.getMyStr());
    }
    public static void main(String[] args) {
        // 建立Spring上下文
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //獲取bean的實例
        HelloSpring helloSpring=(HelloSpring)context.getBean("myFirstSpringDemo");
        helloSpring.Print();
  
    }

}

二、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
    <bean id="myFirstSpringDemo" class="com.pb.HelloSpring">
        <property name="myStr">
            <value>我是Spring</value>
        </property>
    </bean>
</beans>

 運行效果spring

 

三、注意點


 * 注意點1:依賴注入的是靠 get和set方法的名字來確認的,好比本例子中是getMyStr和setMyStr,那麼Bean裏的屬性名字就必須配置爲myStr,不然出錯
 * 注意點2:Bean的屬性名字必須是首字母小寫,如本例中是 myStr,不能寫成MyStr,不然報[Invalid property 'MyStr' of bean class [com.pb.HelloSpring]: No property 'MyStr' found]
 * 注意點3:get和set方法必須對應起來,不能是這樣 getMYStr和setMyStr,大小寫不一致也會出錯

app

相關文章
相關標籤/搜索