需求大概如下,在枚举对象LAYER_CARETAKER中调用@Autowried注解进行注入, 但是发现layerMapper结果为null。
private enum Caretaker{
LAYER_CARETAKER(LAYER){
@Autowired
private LayerMapper layerMapper;
@Override
public List<TreeNodeVO> childrenNodes(Long parentId) {
List<Layer> floorList = floorMapper.selectList(new EntityWrapper<>());
return floorList.stream()
.map(item-> new TreeNodeVO(item.getId(),item.getName(),getGrade()))
.collect(Collectors.toList());
}
};
// 省略属性、方法
}
然后我改为了:
@Service
@Slf4j
public class CourseArrangementServiceImpl implements CourseArrangementService, ApplicationContextAware {
// 注意
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Caretaker.setApplicationContext(applicationContext);
}
//---------------------------------
@Slf4j
private enum Caretaker implements TreeNodeCaretaker {
/**
*
*/
LAYER_CARETAKER(LAYER){
@Override
public List<TreeNodeVO> childrenNodes(Long parentId) {
LayerMapper floorMapper = getApplicationContext().getBean("layerMapper", LayerMapper.class);
List<Layer> floorList = floorMapper.selectList(new EntityWrapper<>());
return floorList.stream()
.map(item-> new TreeNodeVO(item.getId(),item.getName(),getGrade()))
.collect(Collectors.toList());
}
},
;
private static ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public static void setApplicationContext(ApplicationContext applicationContext){
Caretaker.applicationContext = applicationContext;
}
// 略
}
}
如有问题,欢迎指出~