0
点赞
收藏
分享

微信扫一扫

Spring 6.0官方文档示例(19):嵌入式属性的注入


一、实体类定义:

package cn.edu.tju.domain;

public class Name {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Name{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}

package cn.edu.tju.domain;

public class ThingOne {
    private Name name;
    private int age;

    public ThingOne(){
        this.name = new Name();
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "ThingOne{" +
                "name=" + name +
                ", age=" + age +
                '}';
    }
}

二、配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="thingOne" class="cn.edu.tju.domain.ThingOne">
        <property name="age" value="23"/>
        <property name="name.firstName" value="david"/>
        <property name="name.lastName" value="beckham"/>
    </bean>



</beans>

三、获取bean

package cn.edu.tju;

import cn.edu.tju.domain.*;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;

public class Start11 {
    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        new XmlBeanDefinitionReader(context).loadBeanDefinitions("beans7.xml");
        context.refresh();

        ThingOne test = (ThingOne) context.getBean("thingOne");
        System.out.println(test);




    }
}


举报

相关推荐

0 条评论