zoukankan      html  css  js  c++  java
  • spring--setter注入

       setter注入:注意要创建的对象中要有set方法,否则会报错

    person.java student.java

    package com;
    /*
         set&&变量&&构造方法
    */
    public class Person {
      public String name;
      public Integer age;
      public student s;
        public Person() {
            
        }
        
        public Person(String name, Integer age, student s) {
            
            this.name = name;
            this.age = age;
            this.s = s;
        }
    
        public void setS(student s) {
            this.s = s;
        }
    
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
        
    }

     配置文件: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="p" class="com.Person">
          <property name="name" value="李四"></property>
          <property name="age" value="23"></property>
          <property name="s" ref="student"></property>
       </bean>
       <bean id="student" class="com.student"></bean>
    </beans>

    测试:

    package com.di;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.Person;
    public class TestDemo {
    
      @Test
      public void testSetter() {
          ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
          Person p = (Person) ac.getBean("p");
          
          System.out.println(p.name);
          System.out.println(p.age);
          System.out.println(p.s);
      }
      
      
    }

    测试结果:

           

  • 相关阅读:
    浅谈Java中的深拷贝和浅拷贝(转载)
    浅析Java中的final关键字
    Java内部类详解
    那些年震撼我们心灵的音乐
    深入理解Java的接口和抽象类
    Java:类与继承
    Java中的static关键字解析
    Java垃圾回收机制
    java 字节流和字符流的区别 转载
    Java 输入输出流 转载
  • 原文地址:https://www.cnblogs.com/wwww2/p/12597384.html
Copyright © 2011-2022 走看看