spring基礎之二->Spring IOC基本使用

spring IOC基本使用

經過前面的介紹咱們已經知道了Spring中很是重要的一個特性就是IOC,下面咱們將要來看一下如何使用IOC容器,幫助你們更好的體會spring的優點。java

一、spring_helloworld

(1)使用手動加載jar包的方式實現,分爲三個步驟,如今幾乎不用
  • 導包:導入這五個包便可mysql

    commons-logging-1.2.jar spring-beans-5.2.3.RELEASE.jar spring-context-5.2.3.RELEASE.jar spring-core-5.2.3.RELEASE.jar spring-expression-5.2.3.RELEASE.jarspring

  • 寫配置sql

    Person.java數據庫

    package com.mashibing.bean;

    public class Person {
    private int id;
    private String name;
    private int age;
    private String gender;

    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;
    }

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public String getGender() {
    return gender;
    }

    public void setGender(String gender) {
    this.gender = gender;
    }

    @Override
    public String toString() {
    return "Person{" +
    "id=" + id +
    ", name='" + name + ''' +
    ", age=" + age +
    ", gender='" + gender + ''' +
    '}';
    }
    }
    express

    ioc.xmlapache

    <?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.or...">

    <!--註冊一個對象,spring回自動建立這個對象-->
    <!--
    一個bean標籤就表示一個對象
    id:這個對象的惟一標識
    class:註冊對象的徹底限定名
    -->
    <bean id="person" class="com.mashibing.bean.Person">
    <!--使用property標籤給對象的屬性賦值
    name:表示屬性的名稱
    value:表示屬性的值
    -->
    <property name="id" value="1"></property>
    <property name="name" value="zhangsan"></property>
    <property name="age" value="18"></property>
    <property name="gender" value="男"></property>
    </bean>
    </beans>數組

  • 測試

SpringDemoTest.javasession

package com.mashibing.test;

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemoTest {
public static void main(String[] args) {
//ApplicationContext:表示ioc容器
//ClassPathXmlApplicationContext:表示從當前classpath路徑中獲取xml文件的配置
//根據spring的配置文件來獲取ioc容器對象
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
}
}多線程

(2)使用maven的方式來構建項目
  • 建立maven項目

    定義項目的groupId、artifactId

  • 添加對應的pom依賴

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/m...">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mashibing</groupId>
    <artifactId>spring_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
    <!-- https://mvnrepository.com/art... -->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.3.RELEASE</version>
    </dependency>
    </dependencies>
    </project>

  • 編寫代碼

    Person.java

    package com.mashibing.bean;
    public class Person {
    private int id;
    private String name;
    private int age;
    private String gender;

    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;
    }

    public int getAge() {
    return age;
    }

    public void setAge(int age) {
    this.age = age;
    }

    public String getGender() {
    return gender;
    }

    public void setGender(String gender) {
    this.gender = gender;
    }

    @Override
    public String toString() {
    return "Person{" +
    "id=" + id +
    ", name='" + name + ''' +
    ", age=" + age +
    ", gender='" + gender + ''' +
    '}';
    }
    }

  • 測試

    MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
}
}

總結:

以上兩種方式建立spring的項目都是能夠的,可是在如今的企業開發環境中使用更多的仍是maven這樣的方式,無須本身處理jar之間的依賴關係,也無須提早下載jar包,只須要配置相關的pom便可,所以推薦你們使用maven的方式,具體的maven操做你們能夠看maven的詳細操做文檔。

搭建spring項目須要注意的點:

一、必定要將配置文件添加到類路徑中,使用idea建立項目的時候要放在resource目錄下

二、導包的時候別忘了commons-logging-1.2.jar包

細節點:

一、ApplicationContext就是IOC容器的接口,能夠經過此對象獲取容器中建立的對象

二、對象在Spring容器建立完成的時候就已經建立完成,不是須要用的時候才建立

三、對象在IOC容器中存儲的時候都是單例的,若是須要多例須要修改屬性

四、建立對象給屬性賦值的時候是經過setter方法實現的

五、對象的屬性是由setter/getter方法決定的,而不是定義的成員屬性

二、spring對象的獲取及屬性賦值方式

一、經過bean的id獲取IOC容器中的對象(上面已經用過)
二、經過bean的類型獲取對象

MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person bean = context.getBean(Person.class);
System.out.println(bean);
}
}

注意:經過bean的類型在查找對象的時候,在配置文件中不能存在兩個類型一致的bean對象,若是有的話,能夠經過以下方法

MyTest.java

import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("ioc.xml");
Person person = context.getBean("person", Person.class);
System.out.println(person);
}
}

三、經過構造器給bean對象賦值

ioc.xml

<!--給person類添加構造方法-->
<bean id="person2" class="com.mashibing.bean.Person">
    <constructor-arg name="id" value="1"></constructor-arg>
    <constructor-arg name="name" value="lisi"></constructor-arg>
    <constructor-arg name="age" value="20"></constructor-arg>
    <constructor-arg name="gender" value="女"></constructor-arg>
</bean>

<!--在使用構造器賦值的時候能夠省略name屬性,可是此時就要求必須嚴格按照構造器參數的順序來填寫了-->
<bean id="person3" class="com.mashibing.bean.Person">
    <constructor-arg value="1"></constructor-arg>
    <constructor-arg value="lisi"></constructor-arg>
    <constructor-arg value="20"></constructor-arg>
    <constructor-arg value="女"></constructor-arg>
</bean>

<!--若是想不按照順序來添加參數值,那麼能夠搭配index屬性來使用-->
<bean id="person4" class="com.mashibing.bean.Person">
    <constructor-arg value="lisi" index="1"></constructor-arg>
    <constructor-arg value="1" index="0"></constructor-arg>
    <constructor-arg value="女" index="3"></constructor-arg>
    <constructor-arg value="20" index="2"></constructor-arg>
</bean>
<!--當有多個參數個數相同,不一樣類型的構造器的時候,能夠經過type來強制類型-->
將person的age類型設置爲Integer類型
public Person(int id, String name, Integer age) {
    this.id = id;
    this.name = name;
    this.age = age;
    System.out.println("Age");
}

public Person(int id, String name, String gender) {
    this.id = id;
    this.name = name;
    this.gender = gender;
    System.out.println("gender");
}
<bean id="person5" class="com.mashibing.bean.Person">
    <constructor-arg value="1"></constructor-arg>
    <constructor-arg value="lisi"></constructor-arg>
    <constructor-arg value="20" type="java.lang.Integer"></constructor-arg>
</bean>
<!--若是不修改成integer類型,那麼須要type跟index組合使用-->
 <bean id="person5" class="com.mashibing.bean.Person">
    <constructor-arg value="1"></constructor-arg>
    <constructor-arg value="lisi"></constructor-arg>
    <constructor-arg value="20" type="int" index="2"></constructor-arg>
</bean>
四、經過命名空間爲bean賦值,簡化配置文件中屬性聲明的寫法

一、導入命名空間

<?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.or...">

二、添加配置

<bean id="person6" class="com.mashibing.bean.Person" p:id="3" p:name="wangwu" p:age="22" p:gender="男"></bean>

五、爲複雜類型進行賦值操做

在以前的測試代碼中,咱們都是給最基本的屬性進行賦值操做,在正常的企業級開發中還會遇到給各類複雜類型賦值,如集合、數組、其餘對象等。

Person.java

package com.mashibing.bean;

import java.util.*;

public class Person {
private int id;
private String name="dahuang";
private int age;
private String gender;
private Address address;
private String[] hobbies;
private List<Book> books;
private Set<Integer> sets;
private Map<String,Object> maps;
private Properties properties;

public Person(int id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
System.out.println("有參構造器");
}

public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
System.out.println("Age");
}

public Person(int id, String name, String gender) {
this.id = id;
this.name = name;
this.gender = gender;
System.out.println("gender");
}

public Person() {
}

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;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public List<Book> getBooks() {
return books;
}

public void setBooks(List<Book> books) {
this.books = books;
}

public Map<String, Object> getMaps() {
return maps;
}

public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}

public Properties getProperties() {
return properties;
}

public void setProperties(Properties properties) {
this.properties = properties;
}

public String[] getHobbies() {
return hobbies;
}

public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}

public Set<Integer> getSets() {
return sets;
}

public void setSets(Set<Integer> sets) {
this.sets = sets;
}

@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + ''' +
", age=" + age +
", gender='" + gender + ''' +
", address=" + address +
", hobbies=" + Arrays.toString(hobbies) +
", books=" + books +
", sets=" + sets +
", maps=" + maps +
", properties=" + properties +
'}';
}
}

Book.java

package com.mashibing.bean;

public class Book {

private String name;
private String author;
private double price;

public Book() {
}

public Book(String name, String author, double price) {
    this.name = name;
    this.author = author;
    this.price = price;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

@Override
public String toString() {
    return "Book{" +
            "name='" + name + ''' +
            ", author='" + author + ''' +
            ", price=" + price +
            '}';
}

}

Address.java

package com.mashibing.bean;

public class Address {

private String province;
private String city;
private String town;

public Address() {
}

public Address(String province, String city, String town) {
    this.province = province;
    this.city = city;
    this.town = town;
}

public String getProvince() {
    return province;
}

public void setProvince(String province) {
    this.province = province;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getTown() {
    return town;
}

public void setTown(String town) {
    this.town = town;
}

@Override
public String toString() {
    return "Address{" +
            "province='" + province + ''' +
            ", city='" + city + ''' +
            ", town='" + town + ''' +
            '}';
}

}

ioc.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"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.or...
http://www.springframework.or... https://www.springframework.o..."


<!--給複雜類型的賦值都在property標籤內進行-->
<bean id="person" class="com.mashibing.bean.Person">
<property name="name">
<!--賦空值-->
<null></null>
</property>
<!--經過ref引用其餘對象,引用外部bean-->
<property name="address" ref="address"></property>
<!--引用內部bean-->
<!-- <property name="address">
<bean class="com.mashibing.bean.Address">
<property name="province" value="北京"></property>
<property name="city" value="北京"></property>
<property name="town" value="西城區"></property>
</bean>
</property>-->
<!--爲list賦值-->
<property name="books">
<list>
<!--內部bean-->
<bean id="book1" class="com.mashibing.bean.Book">
<property name="name" value="多線程與高併發"></property>
<property name="author" value="馬士兵"></property>
<property name="price" value="1000"></property>
</bean>
<!--外部bean-->
<ref bean="book2"></ref>
</list>
</property>
<!--給map賦值-->
<property name="maps" ref="myMap"></property>
<!--給property賦值-->
<property name="properties">
<props>
<prop key="aaa">aaa</prop>
<prop key="bbb">222</prop>
</props>
</property>
<!--給數組賦值-->
<property name="hobbies">
<array>
<value>book</value>
<value>movie</value>
<value>game</value>
</array>
</property>
<!--給set賦值-->
<property name="sets">
<set>
<value>111</value>
<value>222</value>
<value>222</value>
</set>
</property>
</bean>
<bean id="address" class="com.mashibing.bean.Address">
<property name="province" value="河北"></property>
<property name="city" value="邯鄲"></property>
<property name="town" value="武安"></property>
</bean>
<bean id="book2" class="com.mashibing.bean.Book">
<property name="name" value="JVM"></property>
<property name="author" value="馬士兵"></property>
<property name="price" value="1200"></property>
</bean>
<!--級聯屬性-->
<bean id="person2" class="com.mashibing.bean.Person">
<property name="address" ref="address"></property>
<property name="address.province" value="北京"></property>
</bean>
<!--util名稱空間建立集合類型的bean-->
<util:map id="myMap">
<entry key="key1" value="value1"></entry>
<entry key="key2" value-ref="book2"></entry>
<entry key="key03">
<bean class="com.mashibing.bean.Book">
<property name="name" value="西遊記" ></property>
<property name="author" value="吳承恩" ></property>
<property name="price" value="100" ></property>
</bean>
</entry>
</util:map>
</beans>
六、繼承關係bean的配置

ioc.xml

<bean id="person" class="com.mashibing.bean.Person">
    <property name="id" value="1"></property>
    <property name="name" value="zhangsan"></property>
    <property name="age" value="21"></property>
    <property name="gender" value="男"></property>
</bean>
<!--parent:指定bean的配置信息繼承於哪一個bean-->
<bean id="person2" class="com.mashibing.bean.Person" parent="person">
    <property name="name" value="lisi"></property>
</bean>

若是想實現Java文件的抽象類,不須要將當前bean實例化的話,可使用abstract屬性

<bean id="person" class="com.mashibing.bean.Person" abstract="true">
    <property name="id" value="1"></property>
    <property name="name" value="zhangsan"></property>
    <property name="age" value="21"></property>
    <property name="gender" value="男"></property>
</bean>
<!--parent:指定bean的配置信息繼承於哪一個bean-->
<bean id="person2" class="com.mashibing.bean.Person" parent="person">
    <property name="name" value="lisi"></property>
</bean>
七、bean對象建立的依賴關係

bean對象在建立的時候是按照bean在配置文件的順序決定的,也可使用depend-on標籤來決定順序

ioc.xml

<bean id="book" class="com.mashibing.bean.Book" depends-on="person,address"></bean>
<bean id="address" class="com.mashibing.bean.Address"></bean>
<bean id="person" class="com.mashibing.bean.Person"></bean>
八、bean的做用域控制,是不是單例

ioc.xml

<!--
bean的做用域:singleton、prototype、request、session
默認狀況下是單例的
prototype:多實例的
    容器啓動的時候不會建立多實例bean,只有在獲取對象的時候纔會建立該對象
    每次建立都是一個新的對象
singleton:默認的單例對象
    在容器啓動完成以前就已經建立好對象
    獲取的全部對象都是同一個
-->
<bean id="person4" class="com.mashibing.bean.Person" scope="prototype"></bean>
九、利用工廠模式建立bean對象

在以前的案例中,全部bean對象的建立都是經過反射獲得對應的bean實例,其實在spring中還包含另一種建立bean實例的方式,就是經過工廠模式進行對象的建立

在利用工廠模式建立bean實例的時候有兩種方式,分別是靜態工廠和實例工廠。

靜態工廠:工廠自己不須要建立對象,可是能夠經過靜態方法調用,對象=工廠類.靜態工廠方法名();

實例工廠:工廠自己須要建立對象,工廠類 工廠對象=new 工廠類;工廠對象.get對象名();

PersonStaticFactory.java

package com.mashibing.factory;

import com.mashibing.bean.Person;

public class PersonStaticFactory {

public static Person getPerson(String name){
Person person = new Person();
person.setId(1);
person.setName(name);
return person;
}
}

ioc.xml

<!--
靜態工廠的使用:
class:指定靜態工廠類
factory-method:指定哪一個方法是工廠方法
-->
<bean id="person5" class="com.mashibing.factory.PersonStaticFactory" factory-method="getPerson">
<!--constructor-arg:能夠爲方法指定參數-->
<constructor-arg value="lisi"></constructor-arg>
</bean>

PersonInstanceFactory.java

package com.mashibing.factory;

import com.mashibing.bean.Person;

public class PersonInstanceFactory {
public Person getPerson(String name){
Person person = new Person();
person.setId(1);
person.setName(name);
return person;
}
}

ioc.xml

<!--實例工廠使用-->
<!--建立實例工廠類-->
<bean id="personInstanceFactory" class="com.mashibing.factory.PersonInstanceFactory"></bean>
<!--
factory-bean:指定使用哪一個工廠實例
factory-method:指定使用哪一個工廠實例的方法
-->
<bean id="person6" class="com.mashibing.bean.Person" factory-bean="personInstanceFactory" factory-method="getPerson">
<constructor-arg value="wangwu"></constructor-arg>
</bean>

十、繼承FactoryBean來建立對象

FactoryBean是Spring規定的一個接口,當前接口的實現類,Spring都會將其做爲一個工廠,可是在ioc容器啓動的時候不會建立實例,只有在使用的時候纔會建立對象

MyFactoryBean.java

package com.mashibing.factory;

import com.mashibing.bean.Person;
import org.springframework.beans.factory.FactoryBean;

/**

  • 實現了FactoryBean接口的類是Spring中能夠識別的工廠類,spring會自動調用工廠方法建立實例
    */

public class MyFactoryBean implements FactoryBean<Person> {

/**

  • 工廠方法,返回須要建立的對象
  • @return
  • @throws Exception
    */
    @Override
    public Person getObject() throws Exception {
    Person person = new Person();
    person.setName("maliu");
    return person;
    }


/**

  • 返回建立對象的類型,spring會自動調用該方法返回對象的類型
  • @return
    */
    @Override
    public Class<?> getObjectType() {
    return Person.class;
    }


/**

  • 建立的對象是不是單例對象
  • @return
    */
    @Override
    public boolean isSingleton() {
    return false;
    }

}

ioc.xml

<bean id="myfactorybean" class="com.mashibing.factory.MyFactoryBean"></bean>

十一、bean對象的初始化和銷燬方法

在建立對象的時候,咱們能夠根據須要調用初始化和銷燬的方法

Address.java

package com.mashibing.bean;

public class Address {

private String province;
private String city;
private String town;

public Address() {
    System.out.println("address被建立了");
}

public Address(String province, String city, String town) {
    this.province = province;
    this.city = city;
    this.town = town;
}

public String getProvince() {
    return province;
}

public void setProvince(String province) {
    this.province = province;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getTown() {
    return town;
}

public void setTown(String town) {
    this.town = town;
}

public void init(){
    System.out.println("對象被初始化");
}

public void destory(){
    System.out.println("對象被銷燬");
}

@Override
public String toString() {
    return "Address{" +
            "province='" + province + ''' +
            ", city='" + city + ''' +
            ", town='" + town + ''' +
            '}';
}

}

ioc.xml

<!--bean生命週期表示bean的建立到銷燬

若是bean是單例,容器在啓動的時候會建立好,關閉的時候會銷燬建立的bean
    若是bean是多禮,獲取的時候建立對象,銷燬的時候不會有任何的調用
-->
<bean id="address" class="com.mashibing.bean.Address" init-method="init" destroy-method="destory"></bean>

MyTest.java

import com.mashibing.bean.Address;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("ioc2.xml");
    Address address = context.getBean("address", Address.class);
    System.out.println(address);
    //applicationContext沒有close方法,須要使用具體的子類
    ((ClassPathXmlApplicationContext)context).close();

}

}

十二、配置bean對象初始化方法的先後處理方法

spring中包含一個BeanPostProcessor的接口,能夠在bean的初始化方法的先後調用該方法,若是配置了初始化方法的前置和後置處理器,不管是否包含初始化方法,都會進行調用

MyBeanPostProcessor.java

package com.mashibing.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPostProcessor implements BeanPostProcessor {
/**

  • 在初始化方法調用以前執行
  • @param bean 初始化的bean對象
  • @param beanName xml配置文件中的bean的id屬性
  • @return
  • @throws BeansException
    */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("postProcessBeforeInitialization:"+beanName+"調用初始化前置方法");
    return bean;
    }


/**

  • 在初始化方法調用以後執行
  • @param bean
  • @param beanName
  • @return
  • @throws BeansException
    */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("postProcessAfterInitialization:"+beanName+"調用初始化後綴方法");
    return bean;
    }

}

ioc.xml

<bean id="myBeanPostProcessor" class="com.mashibing.bean.MyBeanPostProcessor"></bean>

三、spring建立第三方bean對象

在Spring中,不少對象都是單實例的,在平常的開發中,咱們常常須要使用某些外部的單實例對象,例如數據庫鏈接池,下面咱們來說解下如何在spring中建立第三方bean實例。

一、導入數據庫鏈接池的pom文件

<!-- https://mvnrepository.com/art... -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!-- https://mvnrepository.com/art... -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

二、編寫配置文件

ioc.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.or...">

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
<property name="url" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
</bean>
</beans>

三、編寫測試文件

MyTest.java

import com.alibaba.druid.pool.DruidDataSource;
import com.mashibing.bean.Address;
import com.mashibing.bean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;

public class MyTest {

public static void main(String[] args) throws SQLException {
    ApplicationContext context = new ClassPathXmlApplicationContext("ioc3.xml");
    DruidDataSource dataSource = context.getBean("dataSource", DruidDataSource.class);
    System.out.println(dataSource);
    System.out.println(dataSource.getConnection());
}

}

四、spring引用外部配置文件

在resource中添加dbconfig.properties

username=root
password=123456
url=jdbc:mysql://localhost:3306/demo
driverClassName=com.mysql.jdbc.Driver

編寫配置文件

<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.or...
http://www.springframework.or...
http://www.springframework.or...">
<!--加載外部配置文件
在加載外部依賴文件的時候須要context命名空間
-->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driverClassName}"></property>
</bean>
</beans>

五、spring基於xml文件的自動裝配

當一個對象中須要引用另一個對象的時候,在以前的配置中咱們都是經過property標籤來進行手動配置的,其實在spring中還提供了一個很是強大的功能就是自動裝配,能夠按照咱們指定的規則進行配置,配置的方式有如下幾種:

default/no:不自動裝配

byName:按照名字進行裝配,以屬性名做爲id去容器中查找組件,進行賦值,若是找不到則裝配null

byType:按照類型進行裝配,以屬性的類型做爲查找依據去容器中找到這個組件,若是有多個類型相同的bean對象,那麼會報異常,若是找不到則裝配null

constructor:按照構造器進行裝配,先按照有參構造器參數的類型進行裝配,沒有就直接裝配null;若是按照類型找到了多個,那麼就使用參數名做爲id繼續匹配,找到就裝配,找不到就裝配null

ioc.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.or...">

<bean id="address" class="com.mashibing.bean.Address">
<property name="province" value="河北"></property>
<property name="city" value="邯鄲"></property>
<property name="town" value="武安"></property>
</bean>
<bean id="person" class="com.mashibing.bean.Person" autowire="byName"></bean>
<bean id="person2" class="com.mashibing.bean.Person" autowire="byType"></bean>
<bean id="person3" class="com.mashibing.bean.Person" autowire="constructor"></bean>
</beans>

六、SpEL的使用

SpEL:Spring Expression Language,spring的表達式語言,支持運行時查詢操做對象

使用#{...}做爲語法規則,全部的大括號中的字符都認爲是SpEL.

ioc.xml

<bean id="person4" class="com.mashibing.bean.Person"> <!--支持任何運算符--> <property name="age" value="#{12*2}"></property> <!--能夠引用其餘bean的某個屬性值--> <property name="name" value="#{address.province}"></property> <!--引用其餘bean--> <property name="address" value="#{address}"></property> <!--調用靜態方法--> <property name="hobbies" value="#{T(java.util.UUID).randomUUID().toString().substring(0,4)}"></property> <!--調用非靜態方法--> <property name="gender" value="#{address.getCity()}"></property> </bean>

相關文章
相關標籤/搜索