JAVA 核心笔记 || [xxx] Spring 之 Bean 继承

Bean 继承

用法

App.java

import com.mj.bean.BeanDog;
import com.mj.bean.BeanLife;
import com.mj.bean.BeanSay;
import com.mj.bean.BeanAnimal;
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("Bean.xml");
        BeanSay sa = (BeanSay) context.getBean("BeanSay");
        sa.setMsg("__Spring");
        sa.talk();

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

        ApplicationContext animalContext = new ClassPathXmlApplicationContext("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();

    }
}


BeanAnimal.java

package com.mj.bean;

public class BeanAnimal {
    private String animalName = "-animal-";
    private String skin = "-animal skin-";

    public void setAnimalName(String animalName) {
        this.animalName = animalName;
    }

    public void setSkin(String skin) {
        this.skin = skin;
    }

    public  void showAnimal(){
        System.out.println(animalName);
        System.out.println(skin);
    }

    public  void showSkin(){
        System.out.println("=animal skin="+skin);
    }
}

BeanDog.java

package com.mj.bean;

public class BeanDog {

    private String animalName = "";
    private String skin = "";

    public void setSkin(String skin) {
        this.skin = skin;
    }

    public void setAnimalName(String animalName) {
        this.animalName = animalName;
    }

    public void showAnimal(){
        System.out.println(animalName);
        System.out.println(skin);
    }

    public  void init(){

    }

    public void destroy(){

    }
}

Bean.xml





    
        
    

    
    
        
        
    

    
        
    

    
        
    



运行

(_-_)
=dog skin=

你可能感兴趣的:(JAVA 核心笔记 || [xxx] Spring 之 Bean 继承)