2019.6.30 Spring注解 bean后置处理器和属性赋值

6.30

  • BeanPostProcessor是一个接口,用于在bean初始化之前和之后调用。(在bean属性赋值之后)

    • 需要实现其中的2个方法
    @Component
    public class MyBeanPostProcessor 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;
        }
    }
    
  • 属性赋值

    • xml文件中可以指定value属性,可以是基本类型的值,可以是springEL表达式(#{}),还可以是配置文件的K/V(${})[需要事先引入context标签库和<context:property-placeholder location="classpath:xxx.properties">]。
    • 注解方式:通过@Value,值可以是xml配置方式的值(基本类型、spel),如果想要取出配置文件中的值进行赋值,需要在配置类加上@PropertySource(value={"classpath:XXX,properties"})
    • 配置文件中的值默认都加载到了Environment中。可以通过其对象的getProperty("XXXX")来获取Value
posted @ 2019-07-01 20:44  X1aoHei  阅读(379)  评论(0编辑  收藏  举报