首页 > 编程语言 > 详细

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

时间:2019-06-05 20:24:53      阅读:78      评论:0      收藏:0      [点我收藏+]

* 构造器注入

* 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());
    }
}

技术分享图片

第二种通过构造器注入

我们修改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>

测试打印

技术分享图片

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

原文:https://www.cnblogs.com/jamal/p/10981558.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!