美文网首页我爱编程
Spring中InitializingBean使用笔记

Spring中InitializingBean使用笔记

作者: 皮多堡 | 来源:发表于2018-05-27 12:05 被阅读0次

    InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会自动执行该方法


    public interface InitializingBean {
    
        /**
         * Invoked by a BeanFactory after it has set all bean properties supplied
         * (and satisfied BeanFactoryAware and ApplicationContextAware).
         * <p>This method allows the bean instance to perform initialization only
         * possible when all bean properties have been set and to throw an
         * exception in the event of misconfiguration.
         * @throws Exception in the event of misconfiguration (such
         * as failure to set an essential property) or if initialization fails.
         */
        void afterPropertiesSet() throws Exception;
    
    }
    

    总结

    1. 这个方法将在所有的属性被初始化后调用,但是会在init前调用。
    2. 但是主要的是如果是延迟加载的话,则马上执行。
      所以可以在类上加上注解:
    import org.springframework.context.annotation.Lazy;
    @Lazy(false)
    

    使用示例

    • 在service属性初始化完成后调用afterPropertiesSet()初始化父类属性
    @Service
    public class ResourcesImageInfoServiceImpl extends BaseServiceImpl<ResourcesImageInfo> implements ResourcesImageInfoService{
    
        @Autowired
        private ResourcesImageInfoRepository resourcesImageInfoRepository;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            super.baseRepository = resourcesImageInfoRepository;
        }
    
    }
    
    • 父类方法中含有公共repository属性属性
    public abstract class BaseServiceImpl <E extends BaseEntity> implements BaseService<E> {
    
        protected static final Logger logger = LoggerFactory.getLogger(BaseService.class);
    
        protected BaseRepository<E> baseRepository;
    

    相关文章

      网友评论

        本文标题:Spring中InitializingBean使用笔记

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