Spring阶段性学习总结(五)Bean之间的关系

时间:2019-09-20
本文章向大家介绍Spring阶段性学习总结(五)Bean之间的关系,主要包括Spring阶段性学习总结(五)Bean之间的关系使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 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" xmlns:p="http://www.springframework.org/schema/p"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <!--bean之间可以设置关系,例如本例设置成parent="person"后,person1的未定义的值会继承person-->
 7     <bean id="person" class="SpringBeansRelationship.Person"
 8           p:name="张浩" p:adress="唐山市" p:age="21" abstract="true"></bean>
 9     <bean id="person1" class="SpringBeansRelationship.Person"
10           p:name="李四" parent="person"></bean>
11 </beans>
 1 package SpringBeansRelationship;
 2 
 3 public class Person {
 4     private String name;
 5     private int age;
 6     private String adress;
 7 
 8     @Override
 9     public String toString() {
10         return "Person{" +
11                 "name='" + name + '\'' +
12                 ", age=" + age +
13                 ", adress='" + adress + '\'' +
14                 '}';
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32 
33     public String getAdress() {
34         return adress;
35     }
36 
37     public void setAdress(String adress) {
38         this.adress = adress;
39     }
40 }
 1 import org.junit.Test;
 2 import org.springframework.context.support.ClassPathXmlApplicationContext;
 3 import org.springframework.context.support.FileSystemXmlApplicationContext;
 4 
 5 
 6 public class Main {
 7     @Test
 8     public void main() {
 9         String path = this.getClass().getClassLoader().getResource("SpringBeansRelationship").getPath();
10         System.out.println(path);
11         String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath();
12         System.out.println(path1);
13         FileSystemXmlApplicationContext fsxac = new FileSystemXmlApplicationContext(path + "/beansRelation.xml");
14         Person person11 = (Person) fsxac.getBean("person1");
15         System.out.println(person11);
16         ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("SpringBeansRelationship/beansRelation.xml");
17         Person person1 = (Person) ctx.getBean("person1");
18         System.out.println(person1);
19 
20     }
21 }

原文地址:https://www.cnblogs.com/zhang188660586/p/11557250.html