JAVA 核心笔记 || [xxx] Spring 之 Bean 加载多个配置文件

Bean 加载多个配置文件

方法

App.java

import com.mj.bean.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.FileNotFoundException;

public class App {



    public static void main(String args[]) throws FileNotFoundException{
        //ClassPathXmlApplicationContext
        ApplicationContext context = new ClassPathXmlApplicationContext("com/mj/xml/Bean.xml");
        BeanSay sa = (BeanSay) context.getBean("BeanSay");
        sa.setMsg("__Spring");
        sa.talk();

        //FileSystemXmlApplicationContext
        ApplicationContext fileContext = new FileSystemXmlApplicationContext("/src/com/mj/xml/Bean.xml");
        BeanSay sa1 = (BeanSay) fileContext.getBean("BeanSay");
        sa1.setMsg("=Spring====");
        sa1.talk();

        ApplicationContext animalContext = new ClassPathXmlApplicationContext("com/mj/xml/Bean.xml");
        BeanAnimal ani =  (BeanAnimal) animalContext.getBean("Animal");
        ani.setAnimalName("dog");
        ani.showAnimal();

        BeanAnimal animal =  (BeanAnimal) animalContext.getBean("Animal");
        animal.setAnimalName("pig");
        animal.showAnimal();

        // init method   destroy method
        BeanLife life = (BeanLife) context.getBean("BeanLife");
        life.showName();

        //BeanDog 继承  BeanAnimal
        BeanDog dog = (BeanDog)context.getBean("BeanDog");
        dog.showAnimal();

        //加载多配置文件
        BeanUser user = (BeanUser)context.getBean("BeanUser");
        user.showUser();

    }
}

BeanUser.java

package com.mj.bean;

public class BeanUser {
    private String uName = "";
    private String id = "";

    public void setId(String id) {
        this.id = id;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public void showUser(){
        System.out.println(uName);
        System.out.println( id );
    }
}

Bean.xml





    
        
    

    
    
        
        
    

    
        
    

    
        
    

    
    


BeanUser.xml





    
        
        
    


运行

mj
1001

你可能感兴趣的:(JAVA 核心笔记 || [xxx] Spring 之 Bean 加载多个配置文件)