天天看點

Spring第一個helloWorldSpringSpring 設計理念編寫第一個HelloWorld程式

Spring

簡介:

輕量級:Spring是非侵入性的-基于Spring開發的應用中的對象可以不依賴于Spring的API

依賴注入(DI—dependdency injection、IOC)

面向切面程式設計:(AOP—aspect oriented programming)

容器:Spring是一個容器,因為它包含并管理應用對象的生命周期

架構:Spring實作類使用簡單的元件配置組合成一個複雜的應用。在Spring中可以使用XML和java注解組合這些對象

一站式:在IOC和AOP的基礎上可以整合各種企業應用的開源架構和優秀的第三方類庫(實際上Spring自身也提供類展現層的SpringMVC和持久層的Spring JDBC)

Spring 設計理念

      Spring是面向Bean的程式設計

Spring 兩大核心技術

     控制反轉(IoC:)将元件對象的控制權從代碼本身轉移到外部容器

            元件化對象的思想:分離關注點,使用接口,不再關注實作

目的:解耦合.實作每個元件時隻關注元件内部的事情

編寫第一個HelloWorld程式

安裝Spring tool suite

     Spring tool suite是一個Eclipse插件,利用該插件可以更友善的在Eclipse平台上開發基于Spring的應用

安裝後将Eclipse進行重新開機

搭建Spring開發環境

把以下jar包加入到工程的classpath下:

Spring第一個helloWorldSpringSpring 設計理念編寫第一個HelloWorld程式

Spring的配置檔案:一個典型的Spring項目需要建立一個或多個Bean的配置檔案,這些配置檔案用于在Spring IOC容器裡配置Bean.Bean的配置檔案可以放在classpath下,也可以放在其它目錄下。

現在可以寫我們的HelloWorld,結構如下:

Spring第一個helloWorldSpringSpring 設計理念編寫第一個HelloWorld程式

applicationContext.xml是Spring的配置檔案

file-->new-->other

Spring第一個helloWorldSpringSpring 設計理念編寫第一個HelloWorld程式

建立以後

效果如下:

Spring第一個helloWorldSpringSpring 設計理念編寫第一個HelloWorld程式

會為我們生成Spring配置檔案的頭資訊,這是我們之前安裝Spring tool suite插件為我們做的

編寫javaBean

我們編寫的javaBean代碼為

package cn.bdqn.spring;

public class HelloSpring {

       //定義who屬性,該屬性的值通過Spring架構進行設定

       private String who=null;

       /**

        * 列印方法

        */

       public  void print(){

              System.out.println("hello,"+this.getWho()+"!");

       }

        * 獲得who

        * @return who

       public String getWho(){

              return who;

        * 設定who

        * @param who

       public void setWho(String who){

              this.who=who;}    

}

編寫Spring的配置檔案

現在編寫我們的Spring配置檔案,代碼如下:

<?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屬性值是我們javaBean的全類名

   id是唯一辨別

   property标簽中的name屬性的值是我們javaBean中的屬性

   value  給name屬性值對應的javaBean中的屬性 設定的值

       -->

       <bean id="HelloSpring" class="cn.bdqn.spring.HelloSpring">

              <property name="who"  value="spring"></property>

       </bean>

</beans>

編寫測試類

編寫測試類,代碼如下:

package cn.bdqn.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.bdqn.spring.HelloSpring;

public class Test {

       public static void main(String[] args) {

//           建立Spring 的IOC容器對象

              ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

/*          從IOC容器中擷取Bean執行個體 "HelloSpring"是我們applicationContext.xml中配置的id屬性的值*/

              HelloSpring bean = (HelloSpring)context.getBean("HelloSpring");

//           調用print方法

              bean.print();   

繼續閱讀