1、Spring之HelloWorld

TZQ_DO_Dreamer發表於2014-11-09
 2. 開發 HelloWorld

1). 搭建環境:

①. 加入 jar 包:

     commons-logging-1.1.1.jar(Spring 日誌依賴的包)
     spring-beans-4.0.0.RELEASE.jar
     spring-context-4.0.0.RELEASE.jar
     spring-core-4.0.0.RELEASE.jar
     spring-expression-4.0.0.RELEASE.jar

②. 通過 Spring 外掛加入 Spring 的配置檔案。檔名任意beans.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">


     </beans>

2). 建立一個 POJO:必須有一個 public 型別的無引數的構造器

     public class HelloWorld {

          private String username;
    
          public void setUsername(String username) {
               System.out.println("setUsername: " + username);
               this.username = username;
          }
    
          public void hello(){
               System.out.println("hello: " + username);
          }
    
          public HelloWorld() {
               System.out.println("HelloWorld's Constructor...");
          }

    
     }

3). 配置 Spring 的配置檔案

     <!-- 1. 配置 bean -->
     <!-- 
          id: bean 在 IOC 容器中的 id
          class: 指向 bean 的全類名. IOC 容器通過反射的方式建立物件. 並把該物件放在 IOC 容器中. 使用 id 屬性來應用該 bean
     -->

     <bean id="helloWorld" class="com.atguigu.spring.helloworld.HelloWorld">

     <!-- 
          2. 配置屬性
          name: 屬性名. setter 風格的.
          value: 屬性值
     -->
     <property name="username" value="Spring"></property>
</bean>

4). 在 Main 方法中測試使用 Spring

//1. 建立 IOC 容器: Spring 會讀取配置檔案. 建立 bean 例項, 併為屬性賦值
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

//2. 從 IOC 容器中獲取 bean
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");

//3. 呼叫 bean 的方法
helloWorld.hello();


相關文章