3111人加入学习
(9人评价)
SSM框架第二季 - Spring入门

制作完成于2018-09-06 使用Eclipse-4.7.3a、JDK8、Spring-5.0.8、Mybatis-3.4.6

价格 免费

构造器注入,依据参数而不是参数名类型,并且依据顺序调用

    //Parameter constructor method1
    public User(String u_username, Pet u_pet) {
        System.out.println("method 1:String ,Pet");
        this.u_username = u_username;
        this.u_pet = u_pet;
    }
    //Parameter constructor method2
        public User(Integer u_username, Pet u_pet) {
            System.out.println("method 2:String ,Pet");
            this.u_username = u_username.toString();
            this.u_pet = u_pet;
        }

创建两个这样的构造器,在applicationContext.xml配置文件中这样配置

<!-- 构造方法注入 -->
<bean name="user1" class="com.chengyang.bean.User">
<!-- name 是注入构造方法的名称,value是注入值类型,ref是注入引用类型 -->
    <constructor-arg name="u_pet" ref="dog"/>
    <constructor-arg name="u_username" value="121" type="java.lang.Integer" />
</bean>使用type指定u_useranme的类型这样就会调用method2 

 

并且会根据在配置文件中的参数顺序调用User类中的构造器

 

[展开全文]

构造函数注入:

配置文件中:

<!-- 构造方法注入 -->
    <bean name="user1" class="com.lingzhihao.bean.User">
    <!-- name 调用构造方法的参数名称 value 是注入值类型   ref注入引用类型 -->
    <!-- type 指定参数的类型 -->
    <!-- index 指定参数的索引位置 -->
        <constructor-arg name="u_username" value="11"  type="java.lang.Integer"  index="0"/>
        <constructor-arg name="petType" ref="dog"/>
    </bean>

 

User类中:
    public User(String u_username, Pet petType) {
        System.out.println("方法1 String, Pet");
        this.u_username = u_username;
        this.petType = petType;
    }
    
    public User(Integer u_username, Pet petType) {
        System.out.println("方法2 Integer, Pet");
        this.u_username = u_username.toString();
        this.petType = petType;
    }
    
    public User( Pet petType,Integer u_username) {
        System.out.println("方法3  Pet ,Integer");
        this.u_username = u_username.toString();
        this.petType = petType;
    }

[展开全文]

 在Bean中有多个构造方法是,可以用type属性来确定那个方法,如果两个构造方法里面的值一样,顺序不一样,可以用Index来确定 第一个是什么类型

[展开全文]

授课教师

SIKI学院老师

课程特色

下载资料(1)
视频(36)

学员动态