Spring学习(三)——DI依赖注入及Bean的作用域

构造器注入

之前的博客中的注入方式都为构造器注入

<beans>
    <bean id="beanOne" class="x.y.ThingOne">
        <constructor-arg ref="beanTwo"/>
        <constructor-arg ref="beanThree"/>
    </bean>

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

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


<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg type="int" value="7500000"/>
    <constructor-arg type="java.lang.String" value="42"/>
</bean>


<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg index="0" value="7500000"/>
    <constructor-arg index="1" value="42"/>
</bean>


<bean id="exampleBean" class="examples.ExampleBean">
    <constructor-arg name="years" value="7500000"/>
    <constructor-arg name="ultimateAnswer" value="42"/>
</bean>

Set注入

依赖注入:set注入

  • 依赖:bean对象的创建依赖于容器

  • 注入:bean中的所有属性由容器注入

  • 环境搭建

创建一个复杂类型及测试用例
在这里插入图片描述

package com.my.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 + '\'' +
                '}';
    }
}



package com.my.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 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 +
                '}';
    }
}

<?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="student" class="com.my.pojo.Student">
        <property name="name" value="奥特曼"/>
    </bean>

</beans>
import com.my.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 student = (Student) context.getBean("student");
        System.out.println(student.getName());

    }
}

在这里插入图片描述

在学生类的名字属性里面注入奥特曼,其他属性没有注入则打印出就为null

  • 八种方式注入

<?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="address" class="com.my.pojo.Address">
        <property name="address" value="xian"/>
    </bean>

    <bean id="student" class="com.my.pojo.Student">
        <!--1、普通值注入-->
        <property name="name" value="奥特曼"/>

        <!--2、bean注入 Address为引用类型-->
        <property name="address" ref="address"/>
        

        <!--3、数组注入-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国</value>
                <value>水浒</value>
                <value>西游记</value>
            </array>
        </property>

        <!--4、List注入-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>看电影</value>
                <value>打篮球</value>
            </list>
        </property>

        <!--5、Map注入-->
        <property name="card">
            <map>
                <entry key="身份证" value="7758521461566"/>
                <entry key="学生证" value="123456789"/>
            </map>
        </property>

        <!--6、Set注入-->
        <property name="games">
            <set>
                <value>王者荣耀</value>
                <value>刺激战场</value>
            </set>
        </property>

        <!--7、null注入-->
        <property name="wife">
            <null/>
        </property>

        <!--8、Properties注入-->
        <property name="info">
            <props>
                <prop key="学号">12345646</prop>
                <prop key="班级">网络182</prop>
            </props>
        </property>

    </bean>

</beans>
  • 测试

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

import java.util.Arrays;

public class MyTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context =  new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");

        System.out.println(student.getName());
        System.out.println(student.getAddress());
        System.out.println(Arrays.toString(student.getBooks()));
        System.out.println(student.getHobbies());
        System.out.println(student.getCard());
        System.out.println(student.getGames());
        System.out.println(student.getWife());
        System.out.println(student.getInfo());
        System.out.println();
        System.out.println("====================================");
        System.out.println(student);
        
    }
}


奥特曼
Address{
    
    address='xian'}
[红楼梦, 三国, 水浒, 西游记]
[听歌, 看电影, 打篮球]
{
    
    身份证=7758521461566, 学生证=123456789}
[王者荣耀, 刺激战场]
null
{
    
    学号=12345646, 班级=网络182}

====================================
Student{
    
    name='奥特曼', address=Address{
    
    address='xian'}, books=[红楼梦, 三国, 水浒, 西游记], hobbies=[听歌, 看电影, 打篮球], card={
    
    身份证=7758521461566, 学生证=123456789}, games=[王者荣耀, 刺激战场], wife='null', info={
    
    学号=12345646, 班级=网络182}}

拓展方式注入

  • p命名空间注入

在这里插入图片描述
p命名空间注入可以直接注入属性:property
需要导入xml约束

<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 name="classic" class="com.example.ExampleBean">
        <property name="email" value="[email protected]"/>
    </bean>

    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="[email protected]"/>
</beans>

创建User实体类

package com.my.pojo;

public class User {
    
    
    private String name;
    private int age;

    public User() {
    
    
    }

    public User(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

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

    @Override
    public String toString() {
    
    
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- p命名空间注入可以直接注入属性:property-->
    <bean id="user" class="com.my.pojo.User" p:name="hehe" p:age="123"/>

</beans>

测试

   @Test
    public void Test(){
    
    
        ApplicationContext context =  new ClassPathXmlApplicationContext("userBean.xml");
        User user =  context.getBean("user",User.class);
        System.out.println(user);

    }

User{
    
    name='hehe', age=123}
  • c命名空间注入

c命名空间注入 可以通过构造器注入:construct-arg
需要导入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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--   p命名空间注入可以直接注入属性:property-->
    <bean id="user" class="com.my.pojo.User" p:name="hehe" p:age="123"/>

    <!--  c命名空间注入 可以通过构造器注入:construct-arg-->
    <bean id="user2" class="com.my.pojo.User" c:name="lalala" c:age="7758521"/>

</beans>

在这里插入图片描述
测试


  
    @Test
    public void Test(){
    
    
        ApplicationContext context =  new ClassPathXmlApplicationContext("userBean.xml");
        User user =  context.getBean("user2",User.class);
        System.out.println(user);
    }


User{
    
    name='lalala', age=7758521}

Bean的作用域

在这里插入图片描述

  • 1、单例模式(Spring默认机制)

在这里插入图片描述

    <bean id="user2" class="com.my.pojo.User" c:name="lalala" c:age="7758521" scope="singleton"/>

  • 2、原型模式:每次从容器中get的时候,都会产生一个新对象

在这里插入图片描述

    <bean id="user2" class="com.my.pojo.User" c:name="lalala" c:age="7758521" scope="prototype"/>


 @Test
    public void Test(){
    
    
        ApplicationContext context =  new ClassPathXmlApplicationContext("userBean.xml");
        User user =  context.getBean("user2",User.class);
        User user2 =  context.getBean("user2",User.class);

        System.out.println(user == user2);
    }
    
false

  • 3、其余的request、session、application只能在web中使用

  • request在请求的作用域中
  • session在一次会话的作用域中
  • application是全局

猜你喜欢

转载自blog.csdn.net/char_m/article/details/111879622