第一個Spring Demo


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

}

2、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>

 運行效果

 

3、注意點


 * 注意點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,大小寫不一致也會出錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM