天天看點

spring IOC set注入方式寫helloworld

1.首先把spring架構所依賴的jar包下好。

2.build path 導入jar包,右鍵項目,build path–》add External Archives --》你下載下傳好jar包所存放的位置

寫一個HelloWorld 類,注意用bean時,如果你寫了構造器,注意不要寫帶參的構造器。

package com.beans;

public class HelloWorld {
       private String name;

   
   // 這裡的set方法對應bean中的propert name
   public void setName2(String name) {
      System.out.println("setName:"+name);
      this.name = name;
   }
    
   public void hello() {
       System.out.println("hello:"+name);
   }
   public HelloWorld() {
      // TODO Auto-generated constructor stub
      System.out.println("helloworld's constructor....");
   }
}      

寫一個主類,開始的時候沒用spring,直接主類調用setName指派,後來用xml檔案的setter注入的方式指派。

package com.beans;

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

public class Main {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    //建立一個HelloWorld 的對象
        //HelloWorld helloWorld=new HelloWorld();
        // 為name屬性指派
      //helloWorld.setName("xiongtong");
       //1.建立spring的IOC容器對象
    //ApplicationContext 代表IOC容器 是 BeanFactory 接口的子接口
    
    // ClassPathXmlApplicationContext: 是 ApplicationContext的實作類,從類路徑下來加載配置檔案
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        
        //2.從IOC容器中擷取bean執行個體
        HelloWorld helloWorld=(HelloWorld)ctx.getBean("helloWorld");
        System.out.println(helloWorld);
        //3.調用hello方法
        helloWorld.hello();
  }

}      

這是.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 
    class :bean 的全類名,通過反射的方式在IOC容器中建立bean,是以要求必須要有無參的構造器
    id: 表示容器中唯一的id
    -->
    
    <bean id="helloWorld" class="com.beans.HelloWorld">
          <property name="name2" value="spring"></property>
    </bean>
    
</beans>