spring应用之Spring的依赖注入的方式四)

* 构造器注入

* setter注入

这两种方式一般情况下使用的概率是setter注入>构造器注入。

下面演示一下这三种方式该怎么去使用!

首先,setter注入。

我们先定义一个Bean叫Person

package pro.jamal.blog.demo5;

/**
 * @author: lyj
 * @Date: 2019/6/4
 */
public class Person {
    private String name;
    private  int 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;
    }
}

使用Spring的xml配置文件,进行setter依赖注入

<?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="person" class="pro.jamal.blog.demo5.Person">
        <!---通过setter注入-->
        <property name="name" value="yongjar"/>
        <property name="age" value="19"/>
    </bean>

</beans>

在Bean里,给成员setter方法,让xml的propertiy产生映射, 并赋予值。

测试

package pro.jamal.blog.demo5;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: lyj
 * @Date: 2019/6/4
 */
public class Client {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context
                 = new ClassPathXmlApplicationContext("pro/jamal/blog/demo5/bean.xml");
        Person person = context.getBean(Person.class);
        System.out.println("名字:"+ person.getName()+",年龄:"+person.getAge());
    }
}

image

第二种通过构造器注入

我们修改Person类,我们给他两个构造器,一个默认无参的构造器,一个两个参数的构造器

package pro.jamal.blog.demo5;

/**
 * @author: lyj
 * @Date: 2019/6/4
 */
public class Person {
    private String name;
    private  int age;

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

    public Person() {
    }

}

修改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 id="person" class="pro.jamal.blog.demo5.Person">
        <!--构造器注入 index从0开始,按构造器的参数赋值-->
        <constructor-arg index="0" value="jamal"/>
        <constructor-arg index="1" value="30"/>
    </bean>

</beans>

测试打印

1559638321(1)

猜你喜欢

转载自www.cnblogs.com/jamal/p/10981558.html