spring使用bean

    • ApplicationContext 应用上下文,加载Spring 框架配置文件
    • 加载classpath:
      • new ClassPathXmlApplicationContext(“applicationContext.xml”);
    • 加载磁盘路径:
      • new FileSystemXmlApplicationContext(“applicationContext.xml”);

@Test // Spring开发 public void demo2() { // 创建一个工厂类. ApplicationContext applicationContext = new ClassPathXmlApplicationContext( "applicationContext.xml"); HelloService helloService = (HelloService) applicationContext.getBean("userService"); helloService.sayHello(); }


Bean的生命周期的11个步骤
    • 1 . bean对象实例化 : instantiate bean
    • 2 . 属性的注入: populate properties : 封装属性
    • 3 . 注入配置的类的名称 : 如果Bean实现BeanNameAware 执行 setBeanName
    • 4 . 注入applicationContext : 如果Bean实现BeanFactoryAware 或者 k 设置工厂 setBeanFactory 或者上下文对象 setApplicationContext
    • 5 . 初始化之前执行操作如果存在类实现 BeanPostProcessor(后处理Bean),执行postProcessBeforeInitialization
      • 需要添加此标签:<bean class="cn.itcast.spring3.demo4.MyBeanPostProcessor"></bean>
      • 6 . 属性设置后执行操作 : 如果Bean实现InitializingBean 执行 afterPropertiesSet
    • 7 . 调用手动设置的初始化方法 : 调用<bean init-method="init"> 指定初始化方法 init
    • 8 . 初始化后执行操作如果存在类实现 BeanPostProcessor(处理Bean),执行 postProcessAfterInitialization
    • 9 . 执行业务处理
    • 10 . 调用销毁的方法 : 如果Bean实现 DisposableBean 执行 destroy
    • 11 . 调用手动销毁方法 : 调用<bean destroy-method="customerDestroy"> 指定销毁方法 customerDestroy

 
原文地址:https://www.cnblogs.com/zhanglijun/p/9083608.html