[Spring入门点滴]利用构造函数和setter注入

构造器方式注入:

  主要是了解构造器方式注入时,参数顺序的区分(index),以及类型的区分(type),以及两者的混合使用;另外就是,当传入的内容有特殊符号时,借助于value标签和CDATA的处理。以保障程序的正常运行!

/**
 * Created by wangzh on 2016/4/26.
 * Description:通过构造器注入实体;
 * 两个构造器区别就是类型不同;
 * 在配置spring时,可以利用index或者type进行区分;
 * 而对于包含特殊符号的值,可以结合<![CDATA[<beijing>^_^]]> 来进行转义;
 */
public class Car {

    private String brand;
    private String city;
    private double price;
    private int maxSpeed;

    public Car(String brand, String city, double price) {
        super();
        this.brand = brand;
        this.city = city;
        this.price = price;
    }

    public Car(String brand, String city, int maxSpeed) {
        super();
        this.brand = brand;
        this.city = city;
        this.maxSpeed = maxSpeed;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand=‘" + brand + ‘\‘‘ +
                ", city=‘" + city + ‘\‘‘ +
                ", price=" + price +
                ", maxSpeed=" + maxSpeed +
                ‘}‘;
    }
}

spring-context.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="helloWorld" class="org.study.java.lessions.spring.HelloWorld" destroy-method="destroyMethod"
          init-method="initMethod">
        <property name="name" value="spring"></property>
    </bean>

    <!--依赖bean注入-->
    <bean id="menBean" class="org.study.java.lessions.spring.Men">
        <property name="person" ref="personBean"></property>
    </bean>
    <!--属性字段赋值-->
    <bean id="personBean" class="org.study.java.lessions.spring.Person">
        <property name="name" value="hager"/>
        <property name="age" value="29"/>
        <property name="sex" value="男"/>
    </bean>

    <!--通过构造器进行注入,同时指定了参数顺序。but,解决不了重载的问题-->
    <!--<bean id="car" class="org.study.java.lessions.spring.Car">-->
    <!--<constructor-arg value="BMW" index="0"/>-->
    <!--<constructor-arg value="beijing" index="1"/>-->
    <!--<constructor-arg value="30.00" index="2"/>-->
    <!--</bean>-->

    <!--解决重载问题:利用type类型区分-->
    <bean id="car" class="org.study.java.lessions.spring.Car">
        <constructor-arg value="BMW" index="0"/>
        <constructor-arg value="beijing" index="1"/>
        <constructor-arg value="30.00" index="2" type="double"/>
    </bean>

    <!--解决包含特殊符号的问题:结合CDATA处理-->
    <bean id="car2" class="org.study.java.lessions.spring.Car">
        <constructor-arg index="0" type="java.lang.String">
            <value><![CDATA[<B`M``W```>^_^]]></value>
        </constructor-arg>
        <constructor-arg value="beijing" index="1"/>
        <constructor-arg value="30.00" index="2"/>
    </bean>
</beans>

测试用例:

/**
 * Created by wangzh on 2016/4/26.
 * Description:
 */
public class ConstructorTest {

    @Test
    public void construct_Test() {
        ApplicationContext atx = new ClassPathXmlApplicationContext(new String[]{"spring-context.xml"});
        //方法一: 通过byName进行获取
        Car car = (Car) atx.getBean("car");
        System.out.println(car.toString());

        //方法二: 利用byType方式注入,但是如果有多个相同类型的,那么就会失败。因为无法辨别用哪个
        // 因为下面我还声明了一个id = car2 但是 type依然是car的bean.
        Car car2 = atx.getBean(Car.class);
        System.out.println(car2.toString());

        Assert.assertNotNull("true");
    }

    @Test
    public void construct2_Test() {
        ApplicationContext atx = new ClassPathXmlApplicationContext(new String[]{"spring-context.xml"});
        Car car = (Car) atx.getBean("car2");
        System.out.println(car.toString());

        Assert.assertNotNull("true");
    }
}

输出结果:

# 利用byType方式获取的话,会提示:不是唯一声明,找到了两个bean.
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.study.java.lessions.spring.Car] is defined: expected single matching bean but found 2: car,car2

# 正常结果如下:利用CDATA包装后的结果
i‘m initMethod.
Car{brand=‘<B`M``W```>^_^‘, city=‘beijing‘, price=30.0, maxSpeed=0}

setter方式注入:

时间: 2025-01-17 14:50:38

[Spring入门点滴]利用构造函数和setter注入的相关文章

Spring入门--控制反转(IOC)与依赖注入(DI)

    1.控制反转(Inversion of Control)与依赖注入(Dependency Injection) 控制反转即IoC (Inversion of Control),它把传统上由程序代码直接操控的对象的调用权交给容器,通过容器来实现对象组件的装配和管理.所谓的"控制反转"概念就是对组件对象控制权的转移,从程序代码本身转移到了外部容器. IoC是一个很大的概念,可以用不同的方式来实现.其主要实现方式有两种:<1>依赖查找(Dependency Lookup)

Spring系列【2】应用setter注入法实现Bean的注入

package cn.com.xf; public class User { private String name; private int age; private String remark; //省略属性的getter/setter方法 @Override public String toString() { return "User [name=" + name + ", age=" + age + ", remark=" + rema

【Spring】Construcotrer注入和setter注入不同的XML写法方式

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文主要讲解了Spring中constructor注入的4种不同写法和sette的3种不同写法 一.constructor注入4种不同写法 通过构造方法注入,就相当于给构造方法的参数传值set注入的缺点是无法清晰表达哪些属性是必须的,哪些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不完全的或无法使用的bean. 第1种方法:直接传值 <!-- constructor方式注入写

Spring学习笔记--initmethod和构造函数、setter方法的加载顺序

今天学习了一下spring中bean的初始化和销毁,突然想了解一下初始化方法跟构造函数及setter方法注入的执行顺序,记录在此,仅作为学习笔记. 当实例化一个bean时,可能需要执行一些初始化操作来确保该bean处于可用状态.同样地,当不再需要bean时,将其从容器中移除是,我们可以还需要按顺序 执行一些清除工作. package com.zp.chapter2; public class Auditorium { private String name; public void doBefo

[Spring实战系列](8)Spring注入方式之setter注入

通常,JavaBean 的属性是私有的,同时拥有一组存取器方法,以setXXX() 和getXXX() 形式存在.Spring 可以借助属性的set方法来配置属性的值,以实现setter方式的注入. 1. 注入简单值 在Spring 中我们可以使用<property> 元素配置Bean 的属性.<property>在许多方面都与<constructor-arg> 类似,只不过一个是通过构造参数来注入值,另一个是通过调用属性的setter 方法来注入值. 举例说明,让我们

Spring依赖注入的Setter注入(通过get和set方法注入)

导入必要的jar包(Spring.jar和commonslogging.jar) 在src目录下建立applicationContext.xml   (Spring 管理 bean的配置文件) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPEING//DTD BEAN//EN" "http://www.springframewor

spring之setter注入

setter注入分为2种 第一:普通属性注入 <bean id="userAction" class="com.xx.action.UserAction"><!--第一种--> <property name="age" value="13"></property><!--第二种--><property name="name"> <

Spring入门IOC和AOP学习笔记

Spring入门IOC和AOP学习笔记 概述 Spring框架的核心有两个: Spring容器作为超级大工厂,负责管理.创建所有的Java对象,这些Java对象被称为Bean. Spring容器管理容器中Bean之间的依赖关系,使用一种叫做"依赖注入"的方式来管理bean之间的依赖关系. Spring有两个核心接口:BeanFactory和ApplicationContext,ApplicationContext是BeanFactory的子接口.它们都可以代表Spring容器,Spri

详解 Spring 3.0 基于 Annotation 的依赖注入实现(转)

使用 @Repository.@Service.@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的开发.@Repository 注解便属于最先引入的一批,它用于将数据访问层 (DAO 层 ) 的类标识为 Spring Bean.具体只需将该注解标注在 DAO 类上即可.同时,为了让 Spring 能够扫描类路径中的类并识别出 @Repository 注解,需要在 XML 配置文件中启用 Bean