gpt4 book ai didi

java - 如何使用ApplicationListener ConfigurableApplicationContext启动的服务

转载 作者:太空宇宙 更新时间:2023-11-04 09:58:34 25 4
gpt4 key购买 nike

我使用springMvc和mybatis。从项目中复制BaseService和BaseServiceImpl。

public interface BaseService<Record, Example> {
//init mybatis mapper
void initMapper();
}

BaseServiceImpl

public abstract class BaseServiceImpl<Mapper, Record, Example> implements BaseService<Record, Example> {

public Mapper mapper;
@Override
public void initMapper() {
this.mapper = SpringContextUtil.getBean(getMapperClass());
}


public Class<Mapper> getMapperClass() {
return (Class<Mapper>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}

EntityServiceImpl

@Service
@Transactional
@BaseService
public class EntityServiceImpl extends BaseServiceImpl<EntityMapper, Entity, EntityExample> implements EntityService {
}

我初始化 BaseService 使用此代码。

@Component
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {

private static final Logger LOGGER = Logger.getLogger(ApplicationContextListener.class);

@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// root application context
if(null == contextRefreshedEvent.getApplicationContext().getParent()) {
LOGGER.debug(">>>>> spring init finished <<<<<");
// call BaseService initMapper method
ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext)contextRefreshedEvent.getApplicationContext();
Map<String, Object> baseServices = applicationContext.getBeansWithAnnotation(BaseService.class);
for(Object service : baseServices.values()) {
try {
Method initMapper = service.getClass().getMethod("initMapper");
initMapper.invoke(service);
} catch (Exception e) {
LOGGER.error("init BaseService initMapper failed", e);
e.printStackTrace();
}
}

}
}

}

项目启动时,entityServiceImpl.initMapper方法已被调用

@Override
public void initMapper() {
this.mapper = SpringContextUtil.getBean(getMapperClass());
}

但是当我在 Controller 中使用entityService时。无法使用已由ApplicationListener初始化的entityService。这就是我尝试使用entityService的方式

@Conroller 
public class LoginController {
@Resource
EntityService EntityService1;
@Autowired
EntityService EntityService2;

EntityService EntityService3 = (EntityService)SpringContextUtil.getBean(EntityService.class);
}

使用Idea调试,我可以找到一个具有非空映射器的EntityService。但在 Controller 中,三个 EntityService 映射器全部为空。我如何将 EntityService 与由 ApplicationListener 初始化的映射器一起使用?

最佳答案

Spring使用beanPostProcessors链,它可以通过CGLIB或动态代理修改您的初始类。所以 this.mapper = SpringContextUtil.getBean(getMapperClass());可能无法按您的预期工作

关于java - 如何使用ApplicationListener ConfigurableApplicationContext启动的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com