欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot如何動(dòng)態(tài)創(chuàng)建Bean示例代碼

 更新時(shí)間:2017年09月07日 14:23:32   作者:西夏一品堂  
這篇文章主要給大家介紹了關(guān)于Spring Boot如何動(dòng)態(tài)創(chuàng)建Bean的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文主要給大家介紹了關(guān)于Spring Boot動(dòng)態(tài)創(chuàng)建Bean的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。

SpringBoot測(cè)試版本: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是一個(gè)可選條件,表示當(dāng)這個(gè)表達(dá)式為true的時(shí)候,才動(dòng)態(tài)創(chuàng)建bean 
 */ 
@ConditionalOnExpression("${my.configuration.enabled}") 
public class DynamicConfiguration 
{ 
 @Autowired 
 private ApplicationContext applicationContext; 
  
 /** 
  * 這個(gè)方法返回Runnable只是一個(gè)幌子,最重要的是執(zhí)行方法里面的代碼 
  */ 
 @Bean 
 public Runnable dynamicConfiguration() throws Exception 
 { 
  ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext; 
  DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)context.getBeanFactory(); 
   
  BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(UserService.class); 
  /** 
   * 設(shè)置屬性 
   */ 
  beanDefinitionBuilder.addPropertyValue("name", "myConfigure"); 
  beanDefinitionBuilder.addPropertyValue("jdbcTemplate", applicationContext.getBean(JdbcTemplate.class)); 
   
  /** 
   * 注冊(cè)到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; 
 } 
} 

之后,就可以使用如下方式獲取對(duì)象了

applicationContext.getBean(UserService.class);
applicationContext.getBean("userService", UserService.class)

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論