在Spring初始化完成之后使用Spring中bean对象
- 通过 ApplicationListener 进行获取,ContextRefreshedEvent 初始化bean对象生成后进行处理
public class MyApplicationRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> {
private Logger logger = LoggerFactory.getLogger(MyApplicationRefreshedEventListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
applicationContext.getBeansOfType(AbsChannelHelp.class).getClass();
OrderService order = applicationContext.getParentBeanFactory().getBean(OrderService.class);
logger.info("==MyApplicationStartedEventListener==");
}
}
- 实现ApplicationContextAware获取
@Component
public class ChannelAccountFactory implements ApplicationContextAware {
/**
* ImmutableMap 的作用就是:可以让java代码也能够创建一个对象常量映射,来保存一些常量映射的键值对。
* CHANNEL_HELP_IMMUTABLE_MAP 用来初始化渠道帮助类与渠道编码的对应关系
*/
private static ImmutableMap<Byte, AbsChannelHelp> CHANNEL_HELP_IMMUTABLE_MAP;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
final ImmutableMap.Builder<Byte, AbsChannelHelp> builder = ImmutableMap.builder();
Map<String, AbsChannelHelp> map = applicationContext.getBeansOfType(AbsChannelHelp.class);
map.forEach((key, value) -> builder.put(value.getCompanyCode(), value));
CHANNEL_HELP_IMMUTABLE_MAP = builder.build();
}
public static <T extends AbsChannelHelp> T getService(Byte channelCode) {
return (T) CHANNEL_HELP_IMMUTABLE_MAP.get(channelCode);
}
}
- bean 里添加@PostConstruct 注解的方法,在初始化完成后会执行该method
@PostConstruct
public final void afterPropertiesSet() throws Exception {
channelSubject.register(getPayChannelType().getValue(), this);
}