Spring学习(4)依赖注入、Spring的配置说明

Spring

依赖注入

注入方法:
1. 构造注入
constructor-arg元素:驱动调用有参数的构造器
2. 设值注入(set方法注入)
property元素:驱动它调用set方法,对象创建出来之后,就立即会被调用
3. 接口注入
不推荐

建议采用设值注入为主,构造注入为辅的注入策略。对于依赖关系无需变化,尽量采用构造注入;而其它依赖关系的注入,则考虑用set注入。

实体类:

public class User {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void show(){
        System.out.println("name="+name);
    }
}

测试类:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {
    	// 获取Spring的上下文对象!(解析beans.xml文件,生成管理相应的Bean对象)
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以!(getBean:参数即为spring配置文件中bean的id)
        User user = (User) context.getBean("123");
        user.show();
    }
}

构造注入

  1. 使用无参构造创建对象,默认!
  2. 假设我们要使用有参构造创建对象。

(1) 下标赋值

<!-- 下标赋值 -->
<bean id="User" class="com.kuang.pojo.User">
    <constructor-arg index="0" value="张三"/>
</bean>

(2) 类型

<!-- 第二种方式:通过类型创建,不建议使用-->
<bean id="User" class="com.kuang.pojo.User">
    <constructor-arg type="java.lang.String" value="张三"/>
</bean>

(3) 参数名

<!-- 第三种:直接通过参数名来设置 -->
<bean id="User" class="com.kuang.pojo.User">
    <constructor-arg name="name" value="张三"/>
</bean>

配置文件(bean.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 id="user" class="com.kuang.pojo.User">
    	<constructor-arg index="0" value="张三"/>
    </bean>
	
	<!-- 第二种,通过类型创建,不建议使用! -->
	<bean id="user" class="com.kuang.pojo.User">
		<constructor-arg type="java.lang.String" value="张三"/>
	</bean>

	<!-- 第三种,直接通过参数名来设置 -->
	<bean id="user" class="com.kuang.pojo.User">
		<constructor-arg name="name" value="张三"/>
	</bean>
</beans>

总结:在配置文件加载的时候,容器中管理的对象就已经初始化了!

设置注入(Set方式注入)【重点】

  • 依赖注入:Set注入!
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入!

【环境搭建】

  1. 复杂类型
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 + '\'' +
                '}';
    }
}

  1. 真实测试对象
    Student:
import java.util.*;
public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    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> getHobbys() {
        return hobbys;
    }

    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }

    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.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}

  1. 配置文件(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 id="address" class="com.kuang.pojo.Address">
        <property name="address" value="西安"/>
    </bean>

    <bean id="student" class="com.kuang.pojo.Student">
        <!-- 第一种,普通值注入,value -->
        <property name="name" value="张三"/>

        <!-- 第二种,Bean注入,ref -->
        <property name="address" ref="address"/>

        <!-- 第三种,数组注入,ref -->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>西游记</value>
                <value>水浒传</value>
                <value>三国演义</value>
            </array>
        </property>

        <!-- list -->
        <property name="hobbys">
            <list>
                <value>听歌</value>
                <value>敲代码</value>
                <value>看书</value>
            </list>
        </property>

        <!-- Map -->
        <property name="card">
            <map>
                <entry key="手机号" value="15112345678"/>
                <entry key="银行卡" value="11646546574688"/>
            </map>
        </property>

        <!-- Set -->
        <property name="games">
            <set>
                 <value>LOL</value>
                 <value>COC</value>
                 <value>BOB</value>
            </set>
        </property>

        <!-- null -->
        <property name="wife">
            <null/>
        </property>

        <!-- Properties -->
        <property name="info">
            <props>
                <prop key="学号">2106589346</prop>
                <prop key="姓名">张三</prop>
                <prop key="性别"></prop>
            </props>
        </property>
    </bean>
</beans>

userbeans.xml

	<!-- p命名空间注入,可以直接注入属性的值:property -->
    <bean id="user" class="com.kuang.pojo.User" p:name="张三" p:age="18"/>

    <!-- c命名空间注入,可以通过构造器注入:construct-args -->
    <bean id="user2" class="com.kuang.pojo.User" c:age="18" c:name="练习" scope="prototype"/>
  1. 测试类:
import com.kuang.pojo.Student;
import com.kuang.pojo.User;
import org.junit.Test;
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.toString());

        /*
        Student{
            name='张三',
            address=Address{address='西安'},
            books=[红楼梦, 西游记, 水浒传, 三国演义],
            hobbys=[听歌, 敲代码, 看书],
            card={
                手机号=15112345678,
                银行卡=11646546574688
            },
            games=[LOL, COC, BOB],
            wife='null',
            info={
                学号=2106589346,
                性别=男,
                姓名=张三
            }
        }
         */
    }

    // p命名测试
    @Test
    public void test2(){
       ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
       User user = context.getBean("user2",User.class);
        User user2 = context.getBean("user2",User.class);
        System.out.println(user.hashCode());
        System.out.println(user2.hashCode());
        System.out.println(user==user2);
    }
}

Spring的配置说明

别名

<!-- 别名,如果添加了别名,我们也可以使用别名获取到这个对象 -->
<alisa name="user" alisa="userNew"/>

Bean的配置

<!--
id: bean的唯一标识符,也就是相当于我们学的对象名
class: bean对象所对应的全限定名 : 包名 + 类型
name: 也是别名,而且name可以同时取多个别名,可以用空格、逗号或者分号分隔 
-->
<bean id="user" class="com.kuang.pojo.User" name="user2 u2,u3;u4">
	<property name="name" value="张三"/>
</bean>

import

这个import,一般用于团队开发使用,它可以将多个配置文件,导入合并为一个

假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!

  • 张三
  • 李四
  • 王五
  • applicationContext.xml
<import resource="beans.xml">
<import resource="beans2.xml">
<import resource="beans3.xml">

使用的时候,直接使用总的配置就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值