描述
使用GenericApplicationContext类的registerBean方法可以在项目运行时注入一个bean,获取GenericApplicationContext可以继承ApplicationContextAware,重写setApplicationContext,里面的参数就是ApplicationContext。文章来源:https://www.toymoban.com/news/detail-630233.html
继承ApplicationContextAware
@RestController
@RequestMapping("/register/bean")
public class RegisterBeanController implements ApplicationContextAware {
private ApplicationContext applicationContext;
// AnnotationConfigServletWebServerApplicationContext
@GetMapping("/example")
public String registerBean() {
GenericApplicationContext genericApplicationContext = (GenericApplicationContext) this.applicationContext;
// ExampleBean没有使用任何的Component注解。
genericApplicationContext.registerBean("ExampleBean", ExampleBean.class);
ExampleBean exampleBean = (ExampleBean) applicationContext.getBean("ExampleBean");
return exampleBean.getBeanData().getName();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
BeanData
@Component
public class BeanData {
public String getName() {
return "BeanData";
}
}
ExampleBean
测试@Autowrite是否生效。文章来源地址https://www.toymoban.com/news/detail-630233.html
public class ExampleBean {
private String name;
@Autowired
private BeanData beanData;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BeanData getBeanData() {
return beanData;
}
}
到了这里,关于SpringBoot运行时注入一个Bean的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!