`

Spring之IOC详解

阅读更多
1. spring ioc简介

IOC(控制反转:Inverse of Control),又称作依赖注入(Dependency Injection),是一种重要的面向对象编程的法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心。


2. springioc实例讲解

新建项目Spring402

Tester.java

package com.andrew.service;
public interface Tester {
    public void test();
}

ZhangSan.java

package com.andrew.service;
public class ZhangSan implements Tester {
    public void test() {
        System.out.println("张三-测试程序");
    }
}

Lisi.java

package com.andrew.service;
public class Lisi implements Tester {
    public void test() {
        System.out.println("李四-测试程序");
    }
}

JavaWork.java

package com.andrew.service;
public class JavaWork {
    private Tester tester;
    public void setTester(Tester tester) {
        this.tester = tester;
    }
    public void doTest() {
        tester.test();
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="zhangsan" class="com.andrew.service.ZhangSan"></bean>
    <bean id="lisi" class="com.andrew.service.Lisi"></bean>
    <bean id="javaWork" class="com.andrew.service.JavaWork">
        <property name="tester" ref="lisi"></property>
    </bean>
</beans>

Test.java

package com.andrew.test;
import com.andrew.service.JavaWork;
import com.andrew.service.Lisi;
public class Test {
    public static void main(String[] args) {
        JavaWork javaWork = new JavaWork();
        javaWork.setTester(new Lisi());
        javaWork.doTest();
    }
}

运行结果:
李四-测试程序

TestSpring.java

package com.andrew.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.service.JavaWork;
public class TestSpring {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        JavaWork javaWork = (JavaWork) ac.getBean("javaWork");
        javaWork.doTest();
    }
}

运行结果:
李四-测试程序


3. 装配一个bean

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="zhangsan" class="com.andrew.service.ZhangSan"></bean>
</beans>


4. 依赖注入

4.1) 属性注入

4.2) 构造函数注入;(通过类型;通过索引;联合使用)

4.3) 工厂方法注入;(非静态工厂,静态工厂)

4.4) 泛型依赖注入;(Spring4整合Hibernate4的时候使用)

新建项目Spring402-02

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    public People() {
        super();
    }
    public People(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    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;
    }
}

PeopleFactory.java

package com.andrew.factory;
import com.andrew.entity.People;
public class PeopleFactory {
    public People createPeople() {
        People p = new People();
        p.setId(5);
        p.setName("小七");
        p.setAge(77);
        return p;
    }
}

PeopleStaticFactory.java

package com.andrew.factory;
import com.andrew.entity.People;
public class PeopleStaticFactory {
    public static People createPeople() {
        People p = new People();
        p.setId(8);
        p.setName("小八");
        p.setAge(88);
        return p;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <!-- people -->
    <bean id="people" class="com.andrew.entity.People"></bean>
    <!-- 1.属性注入 -->
    <bean id="people11" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="11"></property>
    </bean>
    <!-- 2.构造函数注入 -->
    <!-- 2.1 通过类型 -->
    <bean id="people21" class="com.andrew.entity.People">
        <constructor-arg type="int" value="2"></constructor-arg>
        <constructor-arg type="String" value="李四"></constructor-arg>
        <constructor-arg type="int" value="22"></constructor-arg>
    </bean>
    <!-- 2.2 通过索引 -->
    <bean id="people22" class="com.andrew.entity.People">
        <constructor-arg index="0" value="3"></constructor-arg>
        <constructor-arg index="1" value="王五"></constructor-arg>
        <constructor-arg index="2" value="55"></constructor-arg>
    </bean>
    <!-- 2.3 联合使用 -->
    <bean id="people23" class="com.andrew.entity.People">
        <constructor-arg index="0" type="int" value="4"></constructor-arg>
        <constructor-arg index="1" type="String" value="赵六"></constructor-arg>
        <constructor-arg index="2" type="int" value="66"></constructor-arg>
    </bean>
    <!-- 3. 工厂方法注入 -->
    <!-- 3.1 非静态工厂 -->
    <bean id="peopleFactory" class="com.andrew.factory.PeopleFactory"></bean>
    <bean id="people31" factory-bean="peopleFactory" factory-method="createPeople"></bean>
    <!-- 3.2 静态工厂 -->
    <bean id="people32" class="com.andrew.factory.PeopleStaticFactory" factory-method="createPeople"></bean>
</beans>

Test.java

package com.andrew.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class Test {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        People people = (People) ac.getBean("people");
        System.out.println(people);
        // 1.属性注入
        People people11 = (People) ac.getBean("people11");
        System.out.println(people11);
        // 2.构造函数注入
        // 2.1 通过类型
        People people21 = (People) ac.getBean("people21");
        System.out.println(people21);
        // 2.2 通过索引
        People people22 = (People) ac.getBean("people22");
        System.out.println(people22);
        // 2.3 联合使用
        People people23 = (People) ac.getBean("people23");
        System.out.println(people23);
        // 3. 工厂方法注入
        // 3.1 非静态工厂
        People people31 = (People) ac.getBean("people31");
        System.out.println(people31);
        // 3.2 静态工厂
        People people32 = (People) ac.getBean("people32");
        System.out.println(people32);
    }
}

运行结果:
People [id=0, name=null, age=0]
People [id=1, name=张三, age=11]
People [id=2, name=李四, age=22]
People [id=3, name=王五, age=55]
People [id=4, name=赵六, age=66]
People [id=5, name=小七, age=77]
People [id=8, name=小八, age=88]


5. 注入参数

5.1) 基本类型值

5.2) 注入bean

5.3) 内部bean

5.4) null值

5.5) 级联属性

5.6) 集合类型属性

新建项目Spring402-03

导入junit jar包,右键buildPath
junit4.4.jar

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    private List<String> hobbies = new ArrayList<String>();
    private Set<String> loves = new HashSet<String>();
    private Map<String, String> works = new HashMap<String, String>();
    private Properties addresses = new Properties();
    public People() {
        super();
    }
    public People(int id, String name, int age, Dog dog, List<String> hobbies,
            Set<String> loves, Map<String, String> works, Properties addresses) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.dog = dog;
        this.hobbies = hobbies;
        this.loves = loves;
        this.works = works;
        this.addresses = addresses;
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + ", hobbies=" + hobbies
                + ", loves=" + loves + ", works=" + works + ", addresses="
                + addresses + "]";
    }
    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 Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public List<String> getHobbies() {
        return hobbies;
    }
    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }
    public Set<String> getLoves() {
        return loves;
    }
    public void setLoves(Set<String> loves) {
        this.loves = loves;
    }
    public Map<String, String> getWorks() {
        return works;
    }
    public void setWorks(Map<String, String> works) {
        this.works = works;
    }
    public Properties getAddresses() {
        return addresses;
    }
    public void setAddresses(Properties addresses) {
        this.addresses = addresses;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <!-- 1. 基本类型值 -->
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="用户一"></property>
        <property name="age" value="11"></property>
    </bean>
    <!-- 2. 注入bean -->
    <bean id="dog2" class="com.andrew.entity.Dog">
        <property name="name" value="狗2"></property>
    </bean>
    <bean id="people2" class="com.andrew.entity.People">
        <property name="id" value="2"></property>
        <property name="name" value="用户二"></property>
        <property name="age" value="22"></property>
        <property name="dog" ref="dog2"></property>
    </bean>
    <!-- 3. 内部bean -->
    <bean id="people3" class="com.andrew.entity.People">
        <property name="id" value="3"></property>
        <property name="name" value="用户三"></property>
        <property name="age" value="33"></property>
        <property name="dog">
            <bean class="com.andrew.entity.Dog">
                <property name="name" value="狗3"></property>
            </bean>
        </property>
    </bean>
    <!-- 4. 注入null -->
    <bean id="people4" class="com.andrew.entity.People">
        <property name="id" value="4"></property>
        <property name="name" value="用戶四"></property>
        <property name="age" value="44"></property>
        <property name="dog">
            <null></null>
        </property>
    </bean>
    <!-- 5. 级联属性 -->
    <bean id="people5" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="11"></property>
        <property name="dog.name" value="Jack2"></property>
    </bean>
    <!-- 6. 集合类型属性 -->
    <bean id="dog6" class="com.andrew.entity.Dog">
        <property name="name" value="狗6"></property>
    </bean>
    <bean id="people6" class="com.andrew.entity.People">
        <property name="id" value="6"></property>
        <property name="name" value="用戶6"></property>
        <property name="age" value="66"></property>
        <property name="dog" ref="dog6"></property>
        <property name="hobbies">
            <list>
                <value>唱歌</value>
                <value>跳舞</value>
            </list>
        </property>
        <property name="loves">
            <set>
                <value>唱歌2</value>
                <value>跳舞2</value>
            </set>
        </property>
        <property name="works">
            <map>
                <entry>
                    <key><value>上午</value></key>
                    <value>写代码</value>
                </entry>
                <entry>
                    <key><value>下午</value></key>
                    <value>测试代码</value>
                </entry>
            </map>
        </property>
        <property name="addresses">
            <props>
                <prop key="address1">aaaaa</prop>
                <prop key="address2">bbbbb</prop>
            </props>
        </property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    // 1. 基本类型值
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        System.out.println(people.getId() + ":" + people.getName() + ":"
                + people.getAge());
    }
    // 2. 注入bean
    @Test
    public void test2() {
        People people = (People) ac.getBean("people2");
        System.out.println(people.getId() + ":" + people.getName() + ":"
                + people.getAge() + ":" + people.getDog().getName());
    }
    // 3. 内部bean
    @Test
    public void test3() {
        People people = (People) ac.getBean("people3");
        System.out.println(people.getId() + ":" + people.getName() + ":"
                + people.getAge() + ":" + people.getDog().getName());
    }
    // 4. 注入null
    @Test
    public void test4() {
        People people = (People) ac.getBean("people4");
        System.out.println(people.getId() + ":" + people.getName() + ":"
                + people.getAge() + ":" + people.getDog());
    }
    // 5. 级联属性
    // Dog.java
    // private Dog dog = new Dog();
    @Test
    public void test5() {
        People people = (People) ac.getBean("people5");
        System.out.println(people.getId() + ":" + people.getName() + ":"
                + people.getAge() + ":" + people.getDog().getName());
    }
    // 6. 注入集合
    @Test
    public void test6() {
        People people = (People) ac.getBean("people6");
        System.out.println(people);
    }
}

运行结果:
1
1:用户一:11
2
2:用户二:22:狗2
3
3:用户三:33:狗3
4
4:用戶四:44:null
5
1:张三:11:Jack2
6
People [id=6, name=用戶6, age=66, dog=狗6, hobbies=[唱歌, 跳舞], loves=[唱歌2, 跳舞2], works={上午=写代码, 下午=测试代码}, addresses={address2=bbbbb, address1=aaaaa}]


6. Spring自动装配

通过配置default-autowire属性,Spring IOC容器可以自动为程序注入bean;默认是no,不启用自动装配;
建议:自动装配机制慎用,它屏蔽了装配细节,容易产生潜在的错误;
default-autowire的类型有byName,byType,constructor;

新建项目Spring402-04


6.1) byName:通过名称进行自动匹配

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
    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 Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

beans.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.org/schema/beans/spring-beans.xsd"
        default-autowire="byName">
    <bean id="dog1" class="com.andrew.entity.Dog">
        <property name="name" value="狗1"></property>
    </bean>
    <bean id="dog" class="com.andrew.entity.Dog">
        <property name="name" value="狗2"></property>
    </bean>
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="用户一"></property>
        <property name="age" value="11"></property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        System.out.println(people);
    }
}

运行结果:
People [id=1, name=用户一, age=11, dog=狗2]


6.2) byType:根据类型进行自动匹配

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
    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 Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

beans.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.org/schema/beans/spring-beans.xsd"
        default-autowire="byType">
    <bean id="dog1" class="com.andrew.entity.Dog">
        <property name="name" value="狗1"></property>
    </bean>
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="用户一"></property>
        <property name="age" value="11"></property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        System.out.println(people);
    }
}

运行结果:
People [id=1, name=用户一, age=11, dog=狗1]
如果bean里有两个dog会报错


6.3) constructor:和byType类似,只不过它是根据构造方法注入而言的,根据类型,自动注入

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    public People() {
        super();
    }
    public People(Dog dog) {
        super();
        System.out.println("constructor");
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
    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 Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

beans.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.org/schema/beans/spring-beans.xsd"
        default-autowire="byType">
    <bean id="dog1" class="com.andrew.entity.Dog">
        <property name="name" value="狗1"></property>
    </bean>
    <bean id="dog" class="com.andrew.entity.Dog">
        <property name="name" value="狗2"></property>
    </bean>
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="用户一"></property>
        <property name="age" value="11"></property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        System.out.println(people);
    }
}

运行结果:
constructor
People [id=1, name=用户一, age=11, dog=狗2]


7. 方法注入

Springbean作用域默认是单例singleton;可以通过配置prototype,实现多例;
方法注入lookup-method

新建项目Spring402-05

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public abstract class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
    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 abstract Dog getDog();
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="dog" class="com.andrew.entity.Dog" scope="prototype">
        <property name="name" value="Jack"></property>
    </bean>
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="11"></property>
        <lookup-method name="getDog" bean="dog"/>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        People people2 = (People) ac.getBean("people1");
        System.out.println(people.getDog() == people2.getDog());
        System.out.println(ac.getBean("dog") == ac.getBean("dog"));
    }
}

运行结果:
false
false


8. 方法替换

新建项目Spring402-06

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private Dog dog;
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", dog=" + dog.getName() + "]";
    }
    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 Dog getDog() {
        Dog dog = new Dog();
        dog.setName("狗1");
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

People2.java

package com.andrew.entity;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class People2 implements MethodReplacer {
    @Override
    public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable {
        Dog dog = new Dog();
        dog.setName("狗2");
        return dog;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="people1" class="com.andrew.entity.People">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
        <property name="age" value="11"></property>
        <replaced-method name="getDog" replacer="people2"></replaced-method>
    </bean>
    <bean id="people2" class="com.andrew.entity.People2"></bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People people = (People) ac.getBean("people1");
        System.out.println(people.getDog().getName());
    }
}

运行结果:
狗2


9. bean之间的关系

新建项目Spring402-07

9.1) 继承
People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private String className;
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", className=" + className + "]";
    }
    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 getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="abstractPeople" class="com.andrew.entity.People" abstract="true">
        <property name="className" value="高三5班"></property>
        <property name="age" value="19"></property>
    </bean>
    <bean id="zhangsan" parent="abstractPeople">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
    </bean>
    <bean id="lisi" parent="abstractPeople">
        <property name="id" value="2"></property>
        <property name="name" value="李四"></property>
        <property name="age" value="20"></property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People zhangsan = (People) ac.getBean("zhangsan");
        System.out.println(zhangsan);
        People lisi = (People) ac.getBean("lisi");
        System.out.println(lisi);
    }
}

运行结果:
People [id=1, name=张三, age=19, className=高三5班]
People [id=2, name=李四, age=20, className=高三5班]


9.2) 依赖

Authority.java

package com.andrew.service;
public class Authority {
    public Authority() {
        System.out.println("获取权限");
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private String className;
    public People() {
        System.out.println("初始化People");
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", className=" + className + "]";
    }
    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 getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="abstractPeople" class="com.andrew.entity.People" abstract="true">
        <property name="className" value="高三5班"></property>
        <property name="age" value="19"></property>
    </bean>
    <bean id="zhangsan" parent="abstractPeople">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
    </bean>
    <bean id="lisi" parent="abstractPeople">
        <property name="id" value="2"></property>
        <property name="name" value="李四"></property>
        <property name="age" value="20"></property>
    </bean>
    <bean id="authority" class="com.andrew.service.Authority"></bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People zhangsan = (People) ac.getBean("zhangsan");
        System.out.println(zhangsan);
        People lisi = (People) ac.getBean("lisi");
        System.out.println(lisi);
    }
}

运行结果:
初始化People
初始化People
获取权限
People [id=1, name=张三, age=19, className=高三5班]
People [id=2, name=李四, age=20, className=高三5班]


在初始化people之前获取权限才可以。这时候我们就需要依赖关系了,people需要在初始化之前依赖authority


beans.xml

<bean id="zhangsan" parent="abstractPeople" depends-on="authority">
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
</bean>

运行结果:
获取权限
初始化People
初始化People
People [id=1, name=张三, age=19, className=高三5班]
People [id=2, name=李四, age=20, className=高三5班]


9.3) 引用

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

People.java

package com.andrew.entity;
public class People {
    private int id;
    private String name;
    private int age;
    private String className;
    private Dog dog;
    public People() {
        System.out.println("初始化People");
    }
    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + ", age=" + age
                + ", className=" + className + ", dog=" + dog + "]";
    }
    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 getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

Authority.java

package com.andrew.service;
public class Authority {
    public Authority() {
        System.out.println("获取权限");
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="dog" class="com.andrew.entity.Dog">
        <property name="name" value="狗1"></property>
    </bean>
    <bean id="abstractPeople" class="com.andrew.entity.People" abstract="true">
        <property name="className" value="高三5班"></property>
        <property name="age" value="19"></property>
    </bean>
    <bean id="zhangsan" parent="abstractPeople" depends-on="authority">
        <property name="id" value="1"></property>
        <property name="name" value="张三"></property>
    </bean>
    <bean id="lisi" parent="abstractPeople">
        <property name="id" value="2"></property>
        <property name="name" value="李四"></property>
        <property name="age" value="20"></property>
    </bean>
    <bean id="authority" class="com.andrew.service.Authority"></bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.People;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        People zhangsan = (People) ac.getBean("zhangsan");
        System.out.println(zhangsan);
        People lisi = (People) ac.getBean("lisi");
        System.out.println(lisi);
    }
}

运行结果:
获取权限
初始化People
初始化People
People [id=1, name=张三, age=19, className=高三5班, dog=null]
People [id=2, name=李四, age=20, className=高三5班, dog=null]


10.  bean作用范围

Dog.java

package com.andrew.entity;
public class Dog {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

beans.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.org/schema/beans/spring-beans.xsd">
    <bean id="dog" class="com.andrew.entity.Dog">
        <property name="name" value="jack"></property>
    </bean>
</beans>

JunitTest.java

package com.andrew.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.andrew.entity.Dog;
public class JunitTest {
    private ApplicationContext ac;
    @Before
    public void setUp() throws Exception {
        ac = new ClassPathXmlApplicationContext("beans.xml");
    }
    @Test
    public void test1() {
        Dog dog = (Dog) ac.getBean("dog");
        Dog dog2 = (Dog) ac.getBean("dog");
        System.out.println(dog == dog2);
    }
}

运行结果:
true


10.1) singleton(默认) Spring ioc容器中仅有一个Bean实例,Bean以单例的方式存在;

beans.xml

<bean id="dog" class="com.andrew.entity.Dog" scope="singleton">
    <property name="name" value="jack"></property>
</bean>

运行结果:
true


10.2) prototype每次从容器中调用Bean时,都返回一个新的实例;

beans.xml

<bean id="dog" class="com.andrew.entity.Dog" scope="prototype">
    <property name="name" value="jack"></property>
</bean>

运行结果:
false


10.3) request每次HTTP请求都会创建一个新的Bean;

10.4) session同一个HTTPSession共享一个Bean;

10.5) global session同一个全局Session共享一个Bean,一般用于Portlet应用环境;

10.6) application同一个Application共享一个Bean;
分享到:
评论

相关推荐

    Spring_IOC详解.pdf

    ### Spring_IOC详解:深入探索Spring框架的IOC容器原理 #### 引言 Spring框架作为Java企业级应用开发的基石,其核心组件之一便是IOC(Inverse of Control)容器。IOC容器负责管理应用程序中的对象及其依赖关系,...

    springIoc实现原理

    **Spring Ioc 实现原理详解** Spring Ioc(Inversion of Control,控制反转)是Spring框架的核心特性之一,它改变了传统应用程序中对象的创建和管理方式。在传统的软件设计中,对象的创建和依赖关系的维护通常由...

    maven-spring-ioc

    **Spring IoC 框架详解** Spring框架是Java开发中的一个核心组件,它提供了许多功能,其中最重要的一项就是Inversion of Control(IoC),也称为Dependency Injection(DI)。IoC容器是Spring的核心,它负责管理...

    Spring的IOC原理

    **Spring的IOC原理详解** **一、IoC理论背景** 在面向对象的软件设计中,对象间的耦合是不可避免的,它们通过相互合作实现业务逻辑。这种耦合就像机械手表中的齿轮,彼此啮合共同完成任务。随着软件系统规模的扩大...

    Spring IOC原理详解

    Spring IOC原理详解 Spring IOC(Inversion of Control,控制反转)是 Spring 框架的核心概念,它解决了对象之间的耦合问题,实现了松耦合编程。IOC 的思想是,Spring 容器来实现对象之间的创建、协调工作,而不是...

    Spring框架系列(7) - Spring IOC实现原理详解之IOC初始化流程.doc

    Spring 框架系列(7)- Spring IOC 实现原理详解之 IOC 初始化流程 本文将详细解释 Spring 框架中的 IOC(Inversion of Control,控制反转)实现原理之 IOC 初始化流程。IOC 是一种软件设计模式,用于将软件系统中...

    Spring中IoC的入门实例详解.doc

    Spring中IoC的入门实例详解.doc

    spring_ioc.docx

    【Spring 框架与控制反转 (IOC) 知识详解】 Spring 框架是 Java Web 开发中广泛使用的轻量级框架,其核心特性是控制反转 (IOC) 和依赖注入 (DI)。控制反转是指将对象的创建权从应用程序代码转移到框架,即不再由...

    Spring 之IoC入门实例

    **Spring之IoC入门实例详解** 在Java世界中,Spring框架以其强大的依赖注入(Dependency Injection,简称DI)和控制反转(Inversion of Control,简称IoC)能力而广受赞誉。IoC是一种设计模式,它将对象的创建和...

    Spring-IOC实例

    **Spring-IOC实例详解** Spring框架是Java开发中不可或缺的一部分,尤其在企业级应用中,其Inversion of Control(IoC)容器是其核心特性之一。IoC,也被称为依赖注入(Dependency Injection,DI),是一种设计模式...

    Spring框架系列(6) - Spring IOC实现原理详解之IOC体系结构设计.doc

    Spring 框架的IoC(Inversion of Control,控制反转)实现原理是其核心特性之一,它使得组件之间的依赖关系不再由代码直接管理,而是交由容器负责。本篇文章将详细探讨Spring IoC的体系结构设计,以及如何实现这些...

    Spring的IoC容器

    **Spring的IoC容器详解** Spring框架的核心特性之一是依赖注入(Dependency Injection,简称DI),而实现这一特性的核心组件就是IoC(Inversion of Control)容器。IoC容器是Spring框架的心脏,它负责管理对象的...

    Spring Ioc 注解 依赖注入

    ### Spring IoC与注解依赖注入详解 #### 一、Spring框架简介 Spring框架是由Rod Johnson创建的一个开源项目,最初是为了解决企业级应用开发中的复杂性问题而诞生的。Spring框架的核心特性包括IoC(Inversion of ...

    简单实现Spring的IOC原理详解

    简单实现Spring的IOC原理详解 Spring IOC(Inversion of Control,控制反转)是一种软件设计模式,它将对象的创建和管理交给容器,实现了对象之间的解耦合。Spring IOC容器是Spring框架的核心,用于管理应用程序中...

    Spring IoC功能例子详解.docx

    Spring 框架中的IoC(Inversion of Control,控制反转)是一种设计模式,它将对象的创建和管理权从代码本身转移到一个外部容器,即Spring的IoC容器。在这个例子中,我们将深入理解如何使用IoC并通过一个简单的`...

    Spring IOC 控制反转

    ### Spring IOC控制反转详解 #### 一、Spring框架简介 Spring框架是一个开源的Java平台,提供了全面的基础架构支持,让开发者能够轻松地开发出松耦合的应用程序。它通过依赖注入(Dependency Injection, DI)和...

Global site tag (gtag.js) - Google Analytics