美文网首页
spring IOC容器

spring IOC容器

作者: 李霖神谷 | 来源:发表于2019-11-22 17:51 被阅读0次

    1.生命周期: init-method="init" destroy-method="destroy"在bean创建指定调用的方法,和销毁指定调用的方法
    spring xml文件配置:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="test" class="com.shuai.hello.hello" init-method="init" destroy-method="destroy"></bean>
    </beans>

    bean下的代码:
    public class hello {
    private String massege;

    public void getMassege() {
        System.out.println(this.massege);
    }
    public  void init(){
        System.out.println("我是初始化函数");
    }
    public  void destroy(){
        System.out.println("我是销毁函数");
    }
    public void setMassege(String massege) {
        this.massege = massege;
    }
    

    }

    测试: 使用AbstractApplicationContext实现类调用context.registerShutdownHook();
    public class test {
    public static void main(String[] args) {
    AbstractApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
    hello hello=(hello)context.getBean("test");
    hello.setMassege("ni hao");
    hello.getMassege();
    context.registerShutdownHook();
    }
    }
    2.spring后置处理器:BeanPostProcessor 对任何一个bean初始化之前之后进行一些逻辑操作,需要在xml文件加入实现BeanPostProcessor的bean的配置。
    package com.shuai.hello;

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;

    public class processorHello implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println(beanName);
    return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println(beanName);
    return bean;
    }
    }
    3.bean xml中的继承:parent
    <bean id="child" class="com.shuai.hello.child">
    <property name="message2" value="message2"></property>
    </bean>
    <bean id="parent" class="com.shuai.hello.parent" parent="child">
    <property name="message3" value="message3"></property>
    </bean>
    public class test {
    public static void main(String[] args) {
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    child c= (child) applicationContext.getBean("child");
    c.getMessage2();
    parent p= (parent) applicationContext.getBean("parent");
    p.getMessage2();
    p.getMessage3();
    }
    }
    当parent调用getMessage2的时候调用的是child继承过来的方法,相当于parent类继承了child类

    相关文章

      网友评论

          本文标题:spring IOC容器

          本文链接:https://www.haomeiwen.com/subject/dwmqwctx.html