1. 程式人生 > >Spring框架實例

Spring框架實例

key 框架 控制反轉 ica uname cnblogs 控制 編寫 beans

一,介紹

  Spring框架核心是Ioc控制反轉,只要在容器中註冊以後,依賴從容器中獲取即可

  簡單的理解:需要一個值,在程序中定義一個變量,但是不賦值,只設置set方法,運行時,容器為該變量賦值

二,實例

1.導入框架依賴包,

  web.xml裏會註冊spring監聽

  applicationContext.xml會自動生成

3.編寫實體類

package com.zhaolong.bean;

import java.util.List;

public class Demo1 {
    
    private List<String> list;

    
public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } }

4.註冊並註入需要的值  applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-autowire="byName"> <!-- List通過list標簽註入值 -->
<bean class="com.zhaolong.bean.Demo1" id="demo1"> <property name="list"> <list> <value>張三</value> <value>李四</value> <value>王五</value> <value>張三</value> <value>李四</value> <value>王五</value> </list> </property> </bean> <!-- Set通過set標簽註入值 --> <bean class="com.zhaolong.bean.Demo2" id="demo2"> <property name="set"> <set> <value>張三</value> <value>李四</value> <value>王五</value> <value>張三</value> <value>李四</value> <value>王五</value> </set> </property> </bean> <!-- Map通過 map標簽註入 --> <bean class="com.zhaolong.bean.Demo3" id="demo3"> <property name="map"> <map> <entry key="uname"> <value>張三</value> </entry> <entry key="upass"> <value>123456</value> </entry> </map> </property> </bean> <!-- 給map註入object --> <bean class="com.zhaolong.bean.Demo3" id="demo32"> <property name="map"> <map> <entry key="demo1" value-ref="demo1"/> <entry key="demo2" value-ref="demo2"/> </map> </property> </bean> <!-- 配置3個學生 --> <bean class="com.zhaolong.bean.Student" id="student1"> <property name="sname"> <value>諸葛亮</value> </property> </bean> <bean class="com.zhaolong.bean.Student" id="student2"> <property name="sname"> <value>周瑜</value> </property> </bean> <bean class="com.zhaolong.bean.Student" id="student3"> <property name="sname"> <value>荀彧</value> </property> </bean> </beans>

5.編寫測試,從xml裏提取bean

package com.zhaolong.test;

import java.util.List;

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

import com.zhaolong.bean.Demo1;

public class Demo1Test {
    
    public static void main(String[] args) {
        
        //通過數組的方式指定配置文件
        ApplicationContext ctx=
                new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
        
        Demo1 demo1 = (Demo1) ctx.getBean("demo1");
        
        List<String> list = demo1.getList();
        
        for (String str : list) {
            System.out.println(str);
        }
        
    }
}

  

Spring框架實例