spring02——基于xml的自动装配以及级联注入

先介绍一下级联注入:

项目结构图

Persion类中有PersionCar 属性,同时persionCar中也有Source属性:

这里注意,一定要写各级联属性的get方法,否则配置文件叫报错

xml配置:

    <bean id="car" class="com.wj.spring.entity2.PersionCar" p:carNam="benchi" p:carPrice="250">
        <property name="source">
            <bean class="com.wj.spring.entity2.Source">
                <property name="sourceNam" value="123"></property>
            </bean>
        </property>
    </bean>
    <bean id="persion" class="com.wj.spring.entity2.Persion" >
        <property name="name" value="bxklx"></property>
        <property name="persionCar" ref="car"></property>
        <property name="persionCar.source.sourceNam" value="测试"></property>
    </bean>
扫描二维码关注公众号,回复: 4789081 查看本文章

结果:

基于xml配置文件也可以实现bean的自动装配:

byName:属性名字要和bean 的 Id 一致!!!

Main方法:

package com.wj.spring.entity2;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by 小美女 on 2018/11/17.
 */
public class Main {
    public static void main(String [] args){
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bean-aut.xml");
        Persion persion = (Persion) ctx.getBean("persion");
        System.out.println(persion);


        Persion persion2 = (Persion) ctx.getBean("persion2");
        System.out.println(persion2);
    }
}

结果:

猜你喜欢

转载自blog.csdn.net/weixin_38520617/article/details/84189956