Spring的配置及jar包下載


一、相關說明

IOC:

Inversion of Control,控制反轉,是面向對象編程中的一種設計原則,可以用來減低計算機代碼之間的耦合度。其中最常見的方式叫做依賴注入(Dependency Injection,簡稱DI)。通過控制反轉,對象在被創建的時候,由一個調控系統內所有對象的外界實體將其所依賴的對象的引用傳遞給它。也可以說,依賴被注入到對象中。簡單地說就是拿到的對象的屬性,已經被注入好相關值了,直接使用即可。 

AOP

在軟件業,AOP為Aspect Oriented Programming的縮寫,意為:面向切面編程,通過預編譯方式和運行期動態代理實現程序功能的統一維護的一種技術。

Spring是一個基於IOC和AOP的結構J2EE系統的框架 

二、配置Spring

1、新建java類型項目

2、導入jar包

現在Spring是放在github上托管,下載步驟如下:

 a、進入spring官網點擊project

b、springfarmework

c、點右邊github標志

 

 d、底部的artifacts

e、Spring Artifactory

 

f、三個版本,一般選第三個,穩定些

g、依次選擇org/springfarmework/spring,然后選擇需要的版本

3、將包導入到項目中

4、在src下建包,新建一個Category類

package com.yyt.pojo;

public class Category {
    private int id;
    private String name;

    

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    

}

5、在src目錄下新建applicationContext.xml文件

applicationContext.xml是Spring的核心配置文件,通過關鍵字c即可獲取Category對象,該對象獲取的時候,即被注入了字符串"category 1“到name屬性中

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context     
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
    <bean name="c" class="com.yyt.pojo.Category">
       
        <property name="name" value="category 1" />
        
    </bean>

  
</beans>

6、test類

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.how2java.pojo.Category;
 
public class Test {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
 
        Category c = (Category) context.getBean("c");
         
        System.out.println(c.getName());
    }
}

三、原理

傳統的方式:
通過new 關鍵字主動創建一個對象
IOC方式
對象的生命周期由Spring來管理,直接從Spring那里去獲取一個對象。 IOC是反轉控制 (Inversion Of Control)的縮寫,就像控制權從本來在自己手里,交給了Spring。

 

注:基於框架的程序要成功運行,對於JAR包的版本,配置文件的正確性有着苛刻的要求,任何一個地方出錯了,都會導致框架程序運行失敗。


免責聲明!

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



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