injecting spring IOC bean bean

Two entities

package com.java.test4;

/**
 * @author nidegui
 * @create 2019-06-22 14:45
 */
public class People {
    private Integer id;
    private String name;
    private String age;
    private Dog dog;

    public Integer getId() {
        return id;
    }

    public People() {
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", dog=" + dog +
                '}';
    }

    public People(Integer id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

  

package com.java.test4;

/**
 * @author nidegui
 * @create 2019-06-22 15:37
 */
public class Dog {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return   " {name=" + name+"}" ;
    }
}

 

beans.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="dog1" class="com.java.test4.Dog">
		<property name="name" value="javk"></property>
 	</bean>
	<bean id="people" class="com.java.test4.People">
		<property name="name" value="nidegui"></property>
		<property name="id" value="1"></property>
		<property name="age" value="12"></property>
		<property name="dog" ref="dog1"></property>
	</bean>

</beans>

  

test:

package com.java.test4;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author nidegui
 * @create 2019-06-22 14:47
 */
public class Test {
    public static void main(String[] args) {
       ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        People people =(People) ac.getBean("people");
        System.out.println(people);
    }
}

  

 

Guess you like

Origin www.cnblogs.com/nidegui/p/11069133.html