Spring IOC控制反转

官方文档: Spring Framework 5
翻译后文档: Spring Framework 5 中文文档

IOC容器

概念:请参考以上文档。
通俗点说法就像是管家(Beans存储管家);主要说一下Bean的依赖注入

新建项目maven躲模块项目引入一下依赖


文档结构

    org.springframework
    spring-core
    ${spring.version}


    org.springframework
    spring-context
    ${spring.version}


    org.springframework
    spring-beans
    ${spring.version}


    org.springframework
    spring-test
    ${spring.version}



    org.projectlombok
    lombok
    1.18.8
    provided


    org.apache.commons
    commons-lang3
    3.8.1

创建Bean

@ToString 
public class MessageBean { 
    private static final Logger logger = Logger.getLogger(MessageBean.class);
    private String message;
    
    public MessageBean() {
        super();
        logger.info("==================无参数构造函数====================");
    } 
    
    public MessageBean(String message) {
        super();
        logger.info("==================有参数构造函数====================");
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
        logger.info("==================setMessage====================");
    } 
    
}
@ToString
public abstract class Animal { 
    private static final Logger logger = Logger.getLogger(Animal.class);
    private String species;
    public abstract void talk();
    public String getSpecies() {
        return species;
    }
    public void setSpecies(String species) {
        this.species = species;
    }
    public Animal() {
        super();
        logger.info("=============Animal 无参数构造方法==============");
    }
    public Animal(String species) {
        super();
        this.species = species;
        logger.info("=============Animal 有参数构造方法==============");
    } 
}
public class Bird extends Animal {
    private static final Logger logger = Logger.getLogger(Bird.class);
    @Override
    public void talk() {
        logger.info("=============Bird.talk==============");
    }
    public Bird() {
        super();
        logger.info("=============Bird 无参数构造方法==============");
    } 
    public Bird(String species) {
        super(species);
        logger.info("=============Bird 有参数构造方法==============");
    }
    
}
public class Dog extends Animal {
    private static final Logger logger = Logger.getLogger(Dog.class);
    @Override
    public void talk() {
        logger.info("=============Dog.talk==============");
    }
    public Dog() {
        super();
        logger.info("=============Dog 无参数构造方法==============");
    } 
    public Dog(String species) {
        super(species);
        logger.info("=============Dog 有参数构造方法==============");
    }

}
XML示例:构造函数 和 工厂模式

创建工厂

public interface AnimalFactory {
    Animal build(String className);
}

工厂实现

public class AnimalFactoryImpl implements AnimalFactory {
    private static final Logger logger = Logger.getLogger(AnimalFactoryImpl.class);
    @Override
    public Animal build(String className) {
        try {
            Class clazz = Class.forName(className);
            Object instance = clazz.newInstance();
            if (instance instanceof Animal) {
                return (Animal) instance;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
}

XML示例



    
    
    
    
    
        
    
    
    
        
    

    
    
        
    
    
        
    

程序入口

public class MainApp {
    private static final Logger logger = Logger.getLogger(MainApp.class);
    public static void main(String[] args) {
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(new DefaultListableBeanFactory());
        reader.loadBeanDefinitions(new ClassPathResource("beans/message-bean.xml"));
        reader.loadBeanDefinitions(new ClassPathResource("beans/animal-bean.xml"));
        BeanFactory beanFactory = (BeanFactory)reader.getBeanFactory();
        MessageBean messageBean_1 = beanFactory.getBean("messageBean_1", MessageBean.class); 
        MessageBean messageBean_2 = beanFactory.getBean("messageBean_2", MessageBean.class);
        MessageBean messageBean_3 = beanFactory.getBean("messageBean_3", MessageBean.class);
        logger.info("messageBean_1===============" + messageBean_1.toString());
        logger.info("messageBean_2===============" + messageBean_2.toString());
        logger.info("messageBean_3===============" + messageBean_3.toString());
        Dog dog = beanFactory.getBean("dog", Dog.class);
        Bird bird = beanFactory.getBean("bird", Bird.class);
        dog.talk();
        bird.talk();
    }
}

执行日志

[INFO ] 2019-06-06 14:09:16,942 method:bertram.wang.beans.MessageBean.(MessageBean.java:19)
==================无参数构造函数====================
[INFO ] 2019-06-06 14:09:16,954 method:bertram.wang.beans.MessageBean.(MessageBean.java:19)
==================无参数构造函数====================
[INFO ] 2019-06-06 14:09:16,974 method:bertram.wang.beans.MessageBean.setMessage(MessageBean.java:34)
==================setMessage====================
[INFO ] 2019-06-06 14:09:16,986 method:bertram.wang.beans.MessageBean.(MessageBean.java:24)
==================有参数构造函数====================
[INFO ] 2019-06-06 14:09:16,986 method:bertram.wang.MainApp.main(MainApp.java:30)
messageBean_1===============MessageBean(message=null)
[INFO ] 2019-06-06 14:09:16,986 method:bertram.wang.MainApp.main(MainApp.java:31)
messageBean_2===============MessageBean(message=set -- 发送一条消息)
[INFO ] 2019-06-06 14:09:16,987 method:bertram.wang.MainApp.main(MainApp.java:32)
messageBean_3===============MessageBean(message=发送一条消息)
[INFO ] 2019-06-06 14:09:16,989 method:bertram.wang.beans.Animal.(Animal.java:24)
=============Animal 无参数构造方法==============
[INFO ] 2019-06-06 14:09:16,989 method:bertram.wang.beans.Dog.(Dog.java:20)
=============Dog 无参数构造方法==============
[INFO ] 2019-06-06 14:09:16,990 method:bertram.wang.beans.Animal.(Animal.java:24)
=============Animal 无参数构造方法==============
[INFO ] 2019-06-06 14:09:16,990 method:bertram.wang.beans.Bird.(Bird.java:19)
=============Bird 无参数构造方法==============
[INFO ] 2019-06-06 14:09:16,990 method:bertram.wang.beans.Dog.talk(Dog.java:16)
=============Dog.talk==============
[INFO ] 2019-06-06 14:09:16,990 method:bertram.wang.beans.Bird.talk(Bird.java:15)
=============Bird.talk==============

居于JAVA注入

@Configuration
public class BeanConfig {
    @Bean
    public AnimalFactory animalFactory() {
        return new AnimalFactoryImpl();
    }
    @Bean
    public Animal dog(AnimalFactory animalFactory) {
        return animalFactory.build("bertram.wang.beans.Dog");
    }
    @Bean
    public Animal bird(AnimalFactory animalFactory) {
        return animalFactory.build("bertram.wang.beans.Bird");
    }
}

程序入口

public class MainApp {
    private static final Logger logger = Logger.getLogger(MainApp.class);
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        //ApplicationContext beanFactory = new ClassPathXmlApplicationContext("beans/message-bean.xml", "beans/animal-bean.xml");
        ApplicationContext beanFactory = new AnnotationConfigApplicationContext(BeanConfig.class);
        /*MessageBean messageBean_1 = beanFactory.getBean("messageBean_1", MessageBean.class); 
        MessageBean messageBean_2 = beanFactory.getBean("messageBean_2", MessageBean.class);
        MessageBean messageBean_3 = beanFactory.getBean("messageBean_3", MessageBean.class);
        logger.info("messageBean_1===============" + messageBean_1.toString());
        logger.info("messageBean_2===============" + messageBean_2.toString());
        logger.info("messageBean_3===============" + messageBean_3.toString());*/
        Dog dog = beanFactory.getBean("dog", Dog.class);
        Bird bird = beanFactory.getBean("bird", Bird.class);
        dog.talk();
        bird.talk();
    }
}

你可能感兴趣的:(Spring IOC控制反转)