我爱编程

Spring中InitializingBean使用笔记

2018-05-27  本文已影响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
public class ResourcesImageInfoServiceImpl extends BaseServiceImpl<ResourcesImageInfo> implements ResourcesImageInfoService{

    @Autowired
    private ResourcesImageInfoRepository resourcesImageInfoRepository;

    @Override
    public void afterPropertiesSet() throws Exception {
        super.baseRepository = resourcesImageInfoRepository;
    }

}
public abstract class BaseServiceImpl <E extends BaseEntity> implements BaseService<E> {

    protected static final Logger logger = LoggerFactory.getLogger(BaseService.class);

    protected BaseRepository<E> baseRepository;
上一篇下一篇

猜你喜欢

热点阅读