运用场景:比如使用热修复的功能,在热加载包里面,增加了 Bean,这个时候可以使用动态加载。
比如动态加载下面的 HotfixActorService 类。
package com.kdhotfix.game;
import com.kd.gameserver.common.BaseService;
import com.kd.gameserver.module.user.dao.ActorDao;
import com.kd.shared.db.game.Actor;
import com.kd.shared.spring.SpringContext;
import litchi.core.Litchi;
import litchi.core.common.extend.ObjectReference;
import litchi.core.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.xbo.hotfix.agent.Installer;
import javax.annotation.PostConstruct;
/**
* 角色逻辑服务
*
* @author paopao
*/
@Component
public class HotfixActorService extends BaseService {
protected static Logger LOGGER = LoggerFactory.getLogger(HotfixActorService.class);
protected static ObjectReference<HotfixActorService> ref = new ObjectReference<>();
@Autowired
ActorDao actorDao;
@Autowired
Litchi litchi;
@PostConstruct
public void register(){
ref.set(this);
}
public Actor getActor(long uid) {
return actorDao.getCacheValue(uid);
}
public boolean existActor(long uid) {
return actorDao.existActor(uid);
}
private static AnnotationConfigApplicationContext context;
public static void updateActorName(long uid, String name){
ref.get().updateName(uid, name);
}
private void updateName(long uid, String name){
Actor actor = getActor(uid);
String oldName = actor.name;
actor.name = "Hello " + name + "-" + DateUtils.getPatternYyyymmddHhmmss_With_DaylightSaving();
update(actor);
LOGGER.debug("注入成功!, 旧名字 {}, 玩家名字 {}", oldName, actor.name);
}
}
static {
//将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) SpringContext.context();
// 获取bean工厂并转换为DefaultListableBeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
// 通过BeanDefinitionBuilder创建bean定义
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(HotfixActorService.class);
// 设置属性userService,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了.
// beanDefinitionBuilder.addPropertyReference("HotfixActorService", "HotfixActorService");
// 注册bean
defaultListableBeanFactory.registerBeanDefinition("HotfixActorService", beanDefinitionBuilder.getRawBeanDefinition());
Object obj = configurableApplicationContext.getBean("HotfixActorService");
if (obj == null){
LOGGER.error("fail to create bean: {}", HotfixActorService.class.getName());
} else {
LOGGER.info("GameHotfixSpringContext init complete...");
}
}