关于java:spring基础之二Spring-IOC基本使用

2次阅读

共计 22639 个字符,预计需要花费 57 分钟才能阅读完成。

spring IOC 根本应用

通过后面的介绍咱们曾经晓得了 Spring 中十分重要的一个个性就是 IOC, 上面咱们将要来看一下如何应用 IOC 容器,帮忙大家更好的领会 spring 的劣势。

1、spring_helloworld

(1) 应用手动加载 jar 包的形式实现,分为三个步骤,当初简直不必
  • 导包:导入这五个包即可

    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.jar

  • 写配置

    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 + ”’ +
    ‘}’;
    }
    }

    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…”>

    <!– 注册一个对象,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.java

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 我的项目须要留神的点:

1、肯定要将配置文件增加到类门路中,应用 idea 创立我的项目的时候要放在 resource 目录下

2、导包的时候别忘了 commons-logging-1.2.jar 包

细节点:

1、ApplicationContext 就是 IOC 容器的接口,能够通过此对象获取容器中创立的对象

2、对象在 Spring 容器创立实现的时候就曾经创立实现,不是须要用的时候才创立

3、对象在 IOC 容器中存储的时候都是单例的,如果须要多例须要批改属性

4、创建对象给属性赋值的时候是通过 setter 办法实现的

5、对象的属性是由 setter/getter 办法决定的,而不是定义的成员属性

2、spring 对象的获取及属性赋值形式

1、通过 bean 的 id 获取 IOC 容器中的对象(下面曾经用过)
2、通过 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);
}
}

3、通过结构器给 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>
4、通过命名空间为 bean 赋值,简化配置文件中属性申明的写法

1、导入命名空间

<?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…”>

2、增加配置

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

5、为简单类型进行赋值操作

在之前的测试代码中,咱们都是给最根本的属性进行赋值操作,在失常的企业级开发中还会遇到给各种简单类型赋值,如汇合、数组、其余对象等。

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>

6、继承关系 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>
7、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>
8、bean 的作用域管制,是否是单例

ioc.xml

<!--
bean 的作用域:singleton、prototype、request、session
默认状况下是单例的
prototype:多实例的
    容器启动的时候不会创立多实例 bean,只有在获取对象的时候才会创立该对象
    每次创立都是一个新的对象
singleton:默认的单例对象
    在容器启动实现之前就曾经创立好对象
    获取的所有对象都是同一个
-->
<bean id="person4" class="com.mashibing.bean.Person" scope="prototype"></bean>
9、利用工厂模式创立 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>

10、继承 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>

11、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();}

}

12、配置 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>

3、spring 创立第三方 bean 对象

在 Spring 中,很多对象都是单实例的,在日常的开发中,咱们常常须要应用某些内部的单实例对象,例如数据库连接池,上面咱们来解说下如何在 spring 中创立第三方 bean 实例。

1、导入数据库连接池的 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>

2、编写配置文件

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>

3、编写测试文件

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

}

4、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>

5、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>

6、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>

正文完
 0