当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot如何动态创建Bean示例代码

Spring Boot如何动态创建Bean示例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

本文主要给大家介绍了关于spring boot动态创建bean的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

springboot测试版本:1.3.4.release

参考代码如下:

package com.spring.configuration; 
 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.beans.factory.support.beandefinitionbuilder; 
import org.springframework.beans.factory.support.defaultlistablebeanfactory; 
import org.springframework.boot.autoconfigure.condition.conditionalonexpression; 
import org.springframework.context.applicationcontext; 
import org.springframework.context.configurableapplicationcontext; 
import org.springframework.context.annotation.bean; 
import org.springframework.context.annotation.configuration; 
import org.springframework.jdbc.core.jdbctemplate; 
 
@configuration 
/** 
 * 这里的conditional是一个可选条件,表示当这个表达式为true的时候,才动态创建bean 
 */ 
@conditionalonexpression("${my.configuration.enabled}") 
public class dynamicconfiguration 
{ 
 @autowired 
 private applicationcontext applicationcontext; 
  
 /** 
  * 这个方法返回runnable只是一个幌子,最重要的是执行方法里面的代码 
  */ 
 @bean 
 public runnable dynamicconfiguration() throws exception 
 { 
  configurableapplicationcontext context = (configurableapplicationcontext)applicationcontext; 
  defaultlistablebeanfactory beanfactory = (defaultlistablebeanfactory)context.getbeanfactory(); 
   
  beandefinitionbuilder beandefinitionbuilder = beandefinitionbuilder.rootbeandefinition(userservice.class); 
  /** 
   * 设置属性 
   */ 
  beandefinitionbuilder.addpropertyvalue("name", "myconfigure"); 
  beandefinitionbuilder.addpropertyvalue("jdbctemplate", applicationcontext.getbean(jdbctemplate.class)); 
   
  /** 
   * 注册到spring容器中 
   */ 
  beanfactory.registerbeandefinition("userservice", beandefinitionbuilder.getbeandefinition()); 
  return null; 
 } 
} 
class userservice 
{ 
 private string name; 
 private jdbctemplate jdbctemplate; 
 public string getname() 
 { 
  return name; 
 } 
 public void setname(string name) 
 { 
  this.name = name; 
 } 
 public jdbctemplate getjdbctemplate() 
 { 
  return jdbctemplate; 
 } 
 public void setjdbctemplate(jdbctemplate jdbctemplate) 
 { 
  this.jdbctemplate = jdbctemplate; 
 } 
} 

之后,就可以使用如下方式获取对象了

applicationcontext.getbean(userservice.class);
applicationcontext.getbean("userservice", userservice.class)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网