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);
  }
  
  
}

测试结果:

       

猜你喜欢

转载自www.cnblogs.com/wwww2/p/12597384.html