Spring阶段性学习总结(二)构造器的方式填充Bean

 1 package SpringBeanDeploy;
 2 
 3 public class Student {
 4     private  String name;
 5     private  int age;
 6     private  String sex;
 7 
 8     public Student(String name, int age) {
 9         this.name = name;
10         this.age = age;
11     }
12 
13     public Student(String name, int age, String sex) {
14         this.name = name;
15         this.age = age;
16         this.sex = sex;
17     }
18 
19     @Override
20     public String toString() {
21         return "Student{" +
22                 "name='" + name + '\'' +
23                 ", age=" + age +
24                 ", sex='" + sex + '\'' +
25                 '}';
26     }
27 }

 

 1 package SpringBeanDeploy;
 2 
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringBeanDeploy/SpringapplicationContext.xml");
 8         Student student = (Student) applicationContext.getBean("Student");
 9         System.out.println(student);
10         student = (Student) applicationContext.getBean("Student1");
11         System.out.println(student);
12     }
13 }

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5     <bean id="Student" class="SpringBeanDeploy.Student">
 6         <constructor-arg value="张浩" index="0"></constructor-arg>
 7         <constructor-arg value="18"></constructor-arg>
 8         <constructor-arg value="男" index="2"></constructor-arg>
 9     </bean>
10     <bean id="Student1" class="SpringBeanDeploy.Student">
11         <constructor-arg value="7" index="1"></constructor-arg>
12         <constructor-arg value="李奔" index="0"></constructor-arg>
13     </bean>
14 </beans>

 

posted @ 2019-09-20 14:45  我叫张小凡  阅读(155)  评论(0编辑  收藏  举报