Spring继承注入与加载多个配置文件

来源:互联网 发布:淘宝怎么做兼职挣钱 编辑:程序博客网 时间:2024/05/18 17:41

一.Spring继承(parent)注入

1.抽象继承类使用 abstract="true"
2.子类继承 parent="父类Id"

二.Spring中引用对象方式:

1. local:在当Xml文件中查找对象
<property name="student3">
     <ref local="student3" />
</property>
2. bean:在所有的Xml文件中查找对象
spring 默认使用bean方式
bean有两种方式
方式一:   
<property name="student3">
     <ref bean="student3" />
</property>
方式二: 
<property name="student3" ref="student3"/>   
3. parent:在父对象中查找

三.使用容器加载多个配置文件

(1)数组方式:
      new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml", "".... });
(2)通配符(*)
      new ClassPathXmlApplicationContext("applicationContext*.xml"});
 注意:配置文件命名统一
 例:名字都是以applicationContext开头
       applicationContext.xml(通用配置)
       applicationContext-web.xml
       applicationContext-biz.xml
       applicationContext-dao.xml

举例:

Student1{studentId,studentName,password}

Student2{studentId,studentName}

Student3{address}

Student4{student2,student3}

两个配置文件

applicationContext.xml中

<!-- 公共类必须定义成 abstract="true",让子类继承parent="student" --><bean id="student" abstract="true"><property name="studentId" value="1" /><property name="studentName" value="老赵" /></bean><bean id="student2" class="com.tarena.entity.Student2" parent="student" />

applicationContext-bean.xml中

<bean id="student1" class="com.tarena.entity.Student1" parent="student"><property name="password" value="123456" /></bean><bean id="student3" class="com.tarena.entity.Student3"><property name="address" value="北京海淀" /></bean><bean id="student4" class="com.tarena.entity.Student4"><property name="student2"><!-- 在当前xml文件中找对象 --><ref bean="student2" /></property><!--<property name="student3"><ref local="student3" /></property>    -->    <property name="student3" ref="student3"/></bean>

测试类:

public class StudetTest {private static Log log = LogFactory.getLog(StudetTest.class);private ApplicationContext ac;@Beforepublic void setUp() {// ac =new ClassPathXmlApplicationContext("applicationContext.xml");/*ac = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml", "applicationContext-bean.xml" });*/ac = new ClassPathXmlApplicationContext("applicationContext*.xml");}@Test@Ignorepublic void testStudent1() {Student1 student = (Student1) ac.getBean("student1");log.info(student.getPassword());log.info(student.getStudentId());log.info(student.getStudentName());}@Test@Ignorepublic void testStudent2() {Student2 student = (Student2) ac.getBean("student2");log.info(student.getStudentId());log.info(student.getStudentName());}@Test@Ignorepublic void testStudent3() {Student3 student = (Student3) ac.getBean("student3");log.info(student.getAddress());}@Test//@Ignorepublic void testStudent4() {Student4 student4 = (Student4) ac.getBean("student4");log.info(student4.getStudent2().getStudentId());log.info(student4.getStudent2().getStudentName());log.info(student4.getStudent3().getAddress());}}