关于SpringBean首次初始化问题

133 阅读1分钟

怎么解决这个问题呢?

在Spring管理的Bean对象中,可以使用以下方法来保证在类第一次执行时进行一些操作

  1. 使用构造方法:在类的构造方法中执行需要的操作。构造方法会在Bean对象被实例化时调用。

  2. 使用@PostConstruct注解:在类中添加一个被@PostConstruct注解修饰的方法,在Bean对象被实例化后,该方法会在依赖注入完成后被自动调用。

  3. 实现InitializingBean接口:让类实现InitializingBean接口,并实现其中的afterPropertiesSet()方法。该方法会在Bean对象被实例化后,依赖注入完成后被自动调用。

*:这些方法可以保证在类第一次执行时进行一些操作,可以根据具体的需求选择其中一种或多种方式来实现。

代码举例

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class ChunyuDiagServiceSingleton {

    @Resource
    private ChunyuDiagUserEnterImpl chunyuDiagUserEnter;
    @Resource
    private ChunyuDiagStartImpl chunyuDiagStart;
    @Resource
    private ChunyuDiagFinishmpl chunyuDiagFinishmpl;
    @Resource
    private ChunyuDiagSummaryImpl chunyuDiagSummary;
    
    private Map<String, ChunyuDiagStrategy> HANDLER_DIAG_MAP;

    @PostConstruct
    private void init(){
        HANDLER_DIAG_MAP = new HashMap<>(4){{
            put(ChunyuConstants.EVENT_TYPE_USER_ENTER, chunyuDiagUserEnter);
            put(ChunyuConstants.EVENT_TYPE_START, chunyuDiagStart);
            put(ChunyuConstants.EVENT_TYPE_FINISH, chunyuDiagFinishmpl);
            put(ChunyuConstants.EVENT_TYPE_SEND_SUMMARY, chunyuDiagSummary);
        }};
    }

    public ChunyuDiagStrategy getChunyuDiagStrategy(String eventType){
        if(!HANDLER_DIAG_MAP.containsKey(eventType)) return null;
        return HANDLER_DIAG_MAP.get(eventType);
    }

    public void doHandle(ChunyuBO chunyuBO){
        ChunyuDiagStrategy chunyuDiagStrategy = getChunyuDiagStrategy(chunyuBO.getEvent_type());
        if(chunyuDiagStrategy == null) return;
        chunyuDiagStrategy.handleDiag(chunyuBO);
    }

}