美文网首页
Spring学习笔记(2)-注入对象

Spring学习笔记(2)-注入对象

作者: 成长的烦恼c | 来源:发表于2019-03-07 14:50 被阅读0次

    在上例Spring IOC/DC中,对Category的name属性注入了"Spring"字符串
    在本例中 ,对Product对象,注入一个Category对象

    1. 创建类Product类,设置和获取Category对象
    package com.jd.java;
    
    public class Product {
    
        private int id;
        private String name;
        private Category category;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Category getCategory() {
            return category;
        }
        public void setCategory(Category category) {
            this.category = category;
        }
    }
    

    2.在创建Product的时候注入一个Category对象。注意:这里要使用ref来注入另一个对象

    <?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="category" class="com.jd.java.Category">
            <property name="name" value="Spring"></property>
        </bean>
    <!--在创建Product的时候注入一个Category对象, 注意,这里要使用ref来注入另一个对象-->
        <bean name="p" class="com.jd.java.Product">
            <property name="name" value="product" />
            <property name="category" ref="category" />
        </bean>
    
    </beans>
    
    1. 通过Spring拿到的Product对象已经被注入了Category对象
    package com.jd.test;
    
    import com.jd.java.Product;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class testSpring {
        public static void main(String[] args){
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
            Product p = (Product) context.getBean("p");
    
            System.out.println(p.getName());
            System.out.println(p.getCategory().getName());
        }
    }
    
    1. 运行结果:


    相关文章

      网友评论

          本文标题:Spring学习笔记(2)-注入对象

          本文链接:https://www.haomeiwen.com/subject/ffmcpqtx.html