zoukankan      html  css  js  c++  java
  • Spring注解-生命周期与属性赋值(二)

    生命周期

    • bean的生命周期
    1. 构造方法
      • 单实例, 在容器启动时创建对象.
      • 多实例, 在每次获取时创建对象.
    2. postProcessBeforeInitialization方法
    3. 初始化
      • 对象创建完成, 并赋值好, 调用初始化方法.
    4. postProcessAfterInitialization方法
    5. 销毁
      • 单实例在容器关闭的时候进行销毁.
      • 多实例, 容器不会管理这个bean, 容器不会调用销毁方法. 需要我们手动调用

    @Bean指定初始化和销毁方法

    • 在@Bean注解中使用initMethoddestoryMethod属性
    1. Car
      public class Car {
      
          public Car() {
              super();
              System.out.println("Car constructor...");
          }
      
          public void init() {
              System.out.println("car ... init...");
          }
          
          public void destory() {
              System.out.println("car .. destory...");
          }
      }
    2. 配置类
      /**
       * bean的生命周期
       *     bean创建 --- 初始化 --- 销毁过程
       * 容器管理bean的生命周期:
       *     我们可以自定义初始化和销毁方法, 容器在bean进行到当前生命周期的时候调用我们自定义的初始化和销毁方法.
       */
      @Configuration
      public class MainConfigOfLifeCycle {
      
          @Bean(initMethod = "init", destroyMethod = "destory")
          public Car car() {
              
              return new Car();
          }
      }

     InitializingBean与DisposableBean

    1. 通过让Bean实现这两个接口, 定义初始化逻辑和销毁逻辑.
      @Component
      public class Cat implements InitializingBean, DisposableBean {
      
          public Cat() {
              super();
              System.out.println("cat constructor...");
          }
      
          @Override
          public void destroy() throws Exception {
              System.out.println("cat...destory...");
          }
      
          @Override
          public void afterPropertiesSet() throws Exception {
              System.out.println("cat...afterPropertiesSet");
          }
      }
    2. 让配置类扫描组件
      @ComponentScan("test.bean")
      @Configuration
      public class MainConfigOfLifeCycle {
      
         //...
      }

    @PostConstruct和@PreDestroy

    1. 使用JSR250规范:
      • @PostConstruct: 在bean创建完成并且属性赋值完成后, 来执行初始化方法.
      • @PreDestroy: 在容器销毁bean之前通知我们进行清理工作.
        @Component
        public class Dog {
        
            public Dog() {
                super();
                System.out.println("Dog constructor...");
            }
        
            //对象创建并赋值之后调用
            @PostConstruct
            public void init() {
                System.out.println("Dog...@PostConstruct");
            }
            
            //容器移除对象之前
            @PreDestroy
            public void destroy() {
                System.out.println("Dog...@PreDestroy");
            }
        }

    BeanPostProcessor

    1. BeanPostProcessor是bean的后置处理器, 在bean初始化前后进行一些处理工作.
      • postProcessBeforeInitialization: 初始化之前
      • postProcessAfterInitialization: 在初始化之后工作.
        //将后置处理器加入到容器中
        @Component
        public class MyBeanPostProcessor implements BeanPostProcessor {
        
            /**
             * bean: 要处理的组件中的bean.
             * beanName: bean的id
             */
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                System.out.println("postProcessBeforeInitialization" + bean + "==>" + beanName);
                return bean;
            }
        
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                System.out.println("postProcessAfterInitialization" + bean + "==>" + beanName);
                return bean;
            }
        
        }

    属性赋值

    @Value注解

    1. 在bean中的属性上加@Value注解可实现赋值.
    2. @Value可赋的值
      • 八大基本类型, String
      • 可以写SpEL: #{ }
      • 可以写${ }: 取出配置文件中的值(在运行环境变量里面的值)
        public class Person {
        
            @Value("张三")
            private String name;
            @Value("#{20-2}")
            private Integer age;
        
            //...
        }

    @PropertySource

    1. 若想取出配置文件中的值实现赋值, 仅用@Value是不行的, 还需要在配置类上使用@PropertySource注解标明配置类的位置.
      • 配置类
        //使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中.
        @PropertySource(value = { "classpath:/person.properties" })
        @Configuration
        public class MainConfigOfPropertyValues {
        
            //...
        }
      • Person
        public class Person {
        
            @Value("张三")
            private String name;
            @Value("#{20-2}")
            private Integer age;
        
            @Value("${person.nickName}")
            private String nickName;
        
            //...
        
        }
    2. 当然, 配置文件中的值还可以从环境变量中获取
          @Test
          public void test01() {
              
              //1.创建ioc容器
              AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
              
              ConfigurableEnvironment environment = ac.getEnvironment();
              
              String property = environment.getProperty("person.nickName");
              System.out.println(property);
              
              ac.close();
          }
  • 相关阅读:
    iOS开发tips-UITableView、UICollectionView行高/尺寸自适应
    10559
    日志系统之基于Zookeeper的分布式协同设计
    IOS 图片上传处理 图片压缩 图片处理
    istream, outstream使用及常见错误
    matlab 扩大虚拟内存
    github不小心同步覆盖了本地文件
    经典统计语言模型
    Makefile 快速入门
    word2vec——高效word特征提取
  • 原文地址:https://www.cnblogs.com/binwenhome/p/13071318.html
Copyright © 2011-2022 走看看