欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring 控制反转(IoC)

程序员文章站 2022-07-12 14:01:17
...

Spring笔记二:

控制反转(IoC):

1、什么是IoC?

IoC,Inversion of Control(控制反转)。

是一种设计思想,在Java开发中,将你设计好的对象交给容器控制,而不是显示地用代码进行对象的创建。

把创建和查找依赖对象的控制权交给 IoC 容器,由 IoC 容器进行注入、组合对象。这样对象与对象之间是松耦合、便于测试、功能可复用(减少对象的创建和内存消耗),使得程序的整个体系结构可维护性、灵活性、扩展性变高。

使用 IoC 的好处:

资源集中管理,实现资源的可配置和易管理
降低了资源的依赖程度,即松耦合
便于测试
功能可复用(减少对象的创建和内存消耗)
使得程序的整个体系结构可维护性、灵活性、扩展性变高

DI(Dependency Injection)依赖注入,是 IoC 容器装配、注入对象的一种方式
通过依赖注入机制,简单的配置即可注入需要的资源,完成自身的业务逻辑,不需要关心资源的出处和具体实现。

spring 提供了三种主要的方式来配置 IoC 容器中的 bean
1.基于 XML 文件配置
2.基于注解配置
3.基于注解 + java 代码显式配置

=DI不是IoC=

2、demo(xml文件配置):

实体类:

package com.itcast.pojo;

public class Hello {
    private String str;

    public Hello() {
    }

    public Hello(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

使用spring配置文件beans.xml
将实体类属性注入值
bean相当于new
对比:
Hello hello = new Hello();
id:变量名 、 class 类型 、 <property 属性注入 ,name字段名 value/ref 注入的值或引用

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="com.itcast.pojo.Hello">
        <property name="str" value="Hello Spring IoC"/>
    </bean>
</beans>

测试:

import com.itcast.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void HelloIoc(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = context.getBean("hello", Hello.class);
        System.out.println(hello.toString());
    }
}

Spring 控制反转(IoC)
【也可以使用构造器注入(不好用)】

3、*.xml配置

①别名:alias / name

    <alias name="hello" alias="abcxyz"/>
    <bean id="hello" class="com.itcast.pojo.Hello">
        <property name="str" value="Hello Spring IoC"/>
    </bean>
<!--    <alias name="hello" alias="abcxyz"/>-->
    <bean id="hello" class="com.itcast.pojo.Hello" name="abcxyz">
        <property name="str" value="Hello Spring IoC"/>
    </bean>

测试:

  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello h1 = context.getBean("abcxyz", Hello.class);
        System.out.println(h1.toString());

② import:
可以将多个配置文件导入到一个配置文件中

4、DI(依赖注入)

①构造器注入(不好用)
②set方式依赖注入
依赖:bean对象的创建依赖于容器
注入:bean对象的属性,由容器来注入
准备:
实体类:
Student

package com.itcast.pojo;

import java.util.*;

public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

    public Student() {
    }

    public Student(String name, Address address, String[] books, List<String> hobbies, Map<String, String> card, Set<String> games, String wife, Properties info) {
        this.name = name;
        this.address = address;
        this.books = books;
        this.hobbies = hobbies;
        this.card = card;
        this.games = games;
        this.wife = wife;
        this.info = info;
    }

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

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

    public String[] getBooks() {
        return books;
    }

    public void setBooks(String[] books) {
        this.books = books;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }

    public Properties getInfo() {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

Address

package com.itcast.pojo;

public class Address {
    private String address;

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}

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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="address" class="com.itcast.pojo.Address">
        <property name="address" value="quanzhou"/>
    </bean>

    <bean name="student" class="com.itcast.pojo.Student">
<!--        普通值注入 value-->
        <property name="name" value="Lutra"/>
<!--        bean注入 ref-->
        <property name="address" ref="address"/>
<!--        数组array-->
        <property name="books">
            <array>
                <value>Java</value>
                <value>MySQL</value>
                <value>Vue</value>
            </array>
        </property>
<!--        list-->
        <property name="hobbies">
            <list>
                <value></value>
                <value></value>
                <value>Rap</value>
            </list>
        </property>
<!--        Map-->
        <property name="card">
            <map>
                <entry key="ID" value="123321"/>
            </map>
        </property>
<!--        Set-->
        <property name="games">
            <set>
                <value>WZRY</value>
                <value>LOL</value>
            </set>
        </property>
<!--        Properties-->
        <property name="info">
            <props>
                <prop key="姓名">kkk</prop>
                <prop key="sex">male</prop>
                <prop key="age">28</prop>
            </props>
        </property>
<!--        null-->
        <property name="wife">
            <null/>
        </property>
    </bean>

</beans>

测试:

import com.itcast.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Student s = context.getBean("student", Student.class);
        System.out.println(s.toString());
    }
}

结果:

Student{name='Lutra', address=Address{address='quanzhou'}, books=[Java, MySQL, Vue], hobbies=[唱, 跳, Rap], card={ID=123321}, games=[WZRY, LOL], wife='null', info={姓名=kkk, sex=male, age=28}}

③其它方式
p命名方式 / c命名方式
p命名方式(set方式):
*.xml导入约束:

xmlns:p="http://www.springframework.org/schema/p"
<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
    https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"
        p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/mydb"
        p:username="root"
        p:password="misterkaoli"/>

</beans>

c命名方式(构造器方式):
*.xml导入约束:

xmlns:c="http://www.springframework.org/schema/c"
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="beanTwo" class="x.y.ThingTwo"/>
    <bean id="beanThree" class="x.y.ThingThree"/>

    <!-- traditional declaration with optional argument names -->
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg name="thingTwo" ref="beanTwo"/>
        <constructor-arg name="thingThree" ref="beanThree"/>
        <constructor-arg name="email" value="aaa@qq.com"/>
    </bean>

    <!-- c-namespace declaration with argument names -->
    <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo"
        c:thingThree-ref="beanThree" c:email="aaa@qq.com"/>
</beans>

5、Bean的作用域

①singleton(默认)
(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
Spring 控制反转(IoC)

<bean id="accountService" class="com.something.DefaultAccountService"/>

<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

②Prototype
Scopes a single bean definition to any number of object instances.
Spring 控制反转(IoC)

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

③Request, Session, Application, and WebSocket Scopes

相关标签: Spring学习笔记