1.先新建一个没有被托管的类
public class UserController implements InitializingBean {
@Autowired
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("我是动态注册的你,不是容器启动的时候注册的你");
}
public String toAction(String content){
return "-->" + userService.doService(content);
}
}
2.接下来在定义一个Spring上下文的工具类
public class SpringContextUtil {
private static ApplicationContext applicationContext;
//获取上下文
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//设置上下文
public static void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
//通过名字获取上下文中的bean
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
//通过类型获取上下文中的bean
public static Object getBean(Class<?> requiredType) {
return applicationContext.getBean(requiredType);
}
}
3.在启动类中注入上下文
public class SpringbootServer4Application {
public static void main(String[] args) {
ApplicationContext app = SpringApplication.run(SpringbootServer4Application.class, args);
SpringContextUtil.setApplicationContext(app);
}
}
4. 核心方法
public class UserControllerT extends SpringbootServer4ApplicationTests {
@Autowired
protected ApplicationContext ctx;
@Test
public void test() {
//将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext)ctx;
// 获取bean工厂并转换为DefaultListableBeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getBeanFactory();
// 通过BeanDefinitionBuilder创建bean定义
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserController.class);
// // 设置属性userService,此属性引用已经定义的bean:userService,这里userService已经被spring容器管理了.
beanDefinitionBuilder.addPropertyReference("userService", "userService");
// 注册bean
defaultListableBeanFactory.registerBeanDefinition("userController", beanDefinitionBuilder.getRawBeanDefinition());
UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController.toAction("动态注册生成调用"));
//删除bean.
//defaultListableBeanFactory.removeBeanDefinition("testService");
}
}