【Spring基础】IOC使用Setter依赖注入

前言

Github:https://github.com/yihonglei/thinking-in-spring(spring-ioc-xml工程)

如果Spring使用XML配置形式,最常用有两种依赖注入方式:setter注入和构造器注入。

这里主要讨论基于setter方法的依赖注入。

一 Setter注入Bean

1、创建一个HelloService接口

package com.jpeony.spring.common;

/**
 * @author yihonglei
 */
public interface HelloService {
    void sayHello(String name);
}

2、HelloServiceImpl实现类

package com.jpeony.spring.common;

/**
 * @author yihonglei
 */
public class HelloServiceImpl implements HelloService {

    @Override
    public void sayHello(String name) {
        System.out.println("hello:" + name);
    }
}

3、创建一个SelfIntroductionService(自我介绍)接口

package com.jpeony.spring.setter;

/**
 * @author yihonglei
 */
public interface SelfIntroductionService {
    void selfIntroduction();
}

4、SelfIntroductionServiceImpl实现类

package com.jpeony.spring.setter;

import com.jpeony.spring.common.HelloService;

/**
 * @author yihonglei
 */
public class SelfIntroductionServiceImpl implements SelfIntroductionService {
    private HelloService helloService;

    /**
     * setter方式注入Bean
     */
    public void setHelloService(HelloService helloService) {
        this.helloService = helloService;
    }

    @Override
    public void selfIntroduction() {
        // 向大家打招呼
        helloService.sayHello("大家好!");
    }

}

5、Spring XML配置applicationContext-Setter-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
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--
        Bean声明:
        该bean类似于javaConfig中的@Bean注解;
        用于创建bean的类通过class属性来指定,并且需要使用全限定的类名。
        通过id指定bean的ID。如果不显示指定,默认使用class的全限定名进行命名。
        eg:
        HelloServiceImpl#0,其#0是一个计数器的形式,
        用来区分相同类型的其他bean。
        使用自动化命名很方便,但是没有多少实际用处,还是建议自己给bean显示设定ID。
    -->
    <bean id="helloService" class="com.jpeony.spring.common.HelloServiceImpl"/>

    <!-- setter注入bean -->
    <bean id="selfIntroductionService" class="com.jpeony.spring.setter.SelfIntroductionServiceImpl">
        <property name="helloService" ref="helloService"/>
    </bean>

</beans>

6. 测试setter注入Bean

package com.jpeony.spring;

import com.jpeony.spring.setter.SelfIntroductionService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试setter注入(bean、字面量、集合)
 *
 * @author yihonglei
 */
public class SetterTest {

    /**
     * 注入bean
     *
     * @author yihonglei
     */
    @Test
    public void testBean() {
        // 根据spring配置文件创建应用上下文
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext-Setter-Bean.xml");
        // 从容器中获取bean
        SelfIntroductionService selfIntroductionService
                = (SelfIntroductionService) context.getBean("selfIntroductionService");
        // 调用自我介绍
        selfIntroductionService.selfIntroduction();
    }

}

7. 运行结果

hello:大家好!
 

总结:

自我介绍类中SelfIntroductionServiceImpl,通过set方法注入bean,

在XML中通过<property name="helloService" ref="helloService"/>指明依赖关系。

二 Setter方法注入字面量

setter方法除了上面应用于注入bean之外,还可以用于注入字面量。

1、创建一个实体类

package com.jpeony.spring.entity;

/**
 * 个人信息(setter注入使用)
 *
 * @author yihonglei
 */
public class PersonSetter {

    /**
     * 姓名
     */
    private String name;
    /**
     * 性别
     */
    private String sex;
    /**
     * 年龄
     */
    private int age;
    /**
     * 兴趣爱好
     */
    private String hobby;

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
}

2、spring配置applicationContext-Setter-Constant.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">
   
    <!-- setter注入字面量 -->
    <bean id="person" class="com.jpeony.spring.entity.Person">
        <property name="name" value="tom"/>
        <property name="sex" value="男"/>
        <property name="age" value="26"/>
        <property name="hobby" value="爱好女人,哈哈!开个玩笑!"/>
    </bean>
    
</beans>

3、测试setter注入字面量

package com.jpeony.spring;

import com.jpeony.spring.entity.PersonSetter;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试setter注入(bean、字面量、集合)
 *
 * @author yihonglei
 */
public class SetterTest {

    /**
     * 注入字面量
     *
     * @author yihonglei
     */
    @Test
    public void testConstant() {
        // 根据spring配置文件创建应用上下文
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext-Setter-Constant.xml");
        // 从容器中获取bean
        PersonSetter person = (PersonSetter) context.getBean("personSetter");
        // 打印个人属性
        System.out.println(" 姓名: " + person.getName() +
                " 性别: " + person.getSex() +
                " 年龄: " + person.getAge() +
                " 兴趣爱好: " + person.getHobby());
    }

}

4、运行结果

姓名: tom 性别: 男 年龄: 26 兴趣爱好: 爱好女人,哈哈!开个玩笑!

三 Setter方法注入集合

setter方法还可以用来注入集合,直接看看实例。

1、创建集合类

package com.jpeony.spring.entity;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Spring 注入集合
 *
 * @author yihonglei
 */
public class Collection {
    private Set<String> set;
    private List<String> list;
    private Map<String, String> map;
    private String[] array;

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public String[] getArray() {
        return array;
    }

    public void setArray(String[] array) {
        this.array = array;
    }

    @Override
    public String toString() {
        return "Collection{" +
                "  set=" + set +
                ", list=" + list +
                ", map=" + map +
                ", array=" + Arrays.toString(array) +
                '}';
    }
}

2、Spring xml配置applicationContext-Setter-List.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">
    
    <!-- setter注入集合 -->
    <bean id="collection" class="com.jpeony.spring.collection.Collection">
        <!-- Set集合的属性注入 -->
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <!-- List集合的属性注入 -->
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <!-- 数组的注入 -->
        <property name="array">
            <list>
                <value>array1</value>
                <value>array1</value>
                <value>array1</value>
            </list>
        </property>
        <!-- Map集合的属性注入 -->
        <property name="map">
            <map>
                <entry key="key1" value="map1"></entry>
                <entry key="key2" value="map2"></entry>
                <entry key="key3" value="map3"></entry>
            </map>
        </property>
    </bean>

</beans>

3、测试Setter注入集合

package com.jpeony.spring;

import com.jpeony.spring.entity.Collection;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试setter注入(bean、字面量、集合)
 *
 * @author yihonglei
 */
public class SetterTest {

    /**
     * 注入集合
     *
     * @author yihonglei
     */
    @Test
    public void testList() {
        // 根据spring配置文件创建应用上下文
        ApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext-Setter-List.xml");
        // 从容器中获取bean
        Collection collection = (Collection) context.getBean("collection");
        // 打印个人属性
        System.out.println("Setter注入集合:" + collection.toString());
    }

}

4、运行结果

Setter注入集合:Collection{  set=[set1, set2, set3], list=[list1, list2, list3], map={key1=map1, key2=map2, key3=map3}, array=[array1, array1, array1]}

四 总结

Spring setter注入可用于注入bean、字面量、集合;

如果是新项目,建议使用Spring注解,因为一堆一堆的xml不好维护,同时功能也不如注解强大。

 

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值