前言
本文主要給大家介紹了關(guān)于Spring Boot動態(tài)創(chuàng)建Bean的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。
SpringBoot測試版本:1.3.4.RELEASE
參考代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
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是一個可選條件,表示當(dāng)這個表達(dá)式為true的時候,才動態(tài)創(chuàng)建bean */ @ConditionalOnExpression ( "${my.configuration.enabled}" ) public class DynamicConfiguration { @Autowired private ApplicationContext applicationContext; /** * 這個方法返回Runnable只是一個幌子,最重要的是執(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 )); /** * 注冊到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; } } |
之后,就可以使用如下方式獲取對象了
1
2
|
applicationContext.getBean(UserService. class ); applicationContext.getBean( "userService" , UserService. class ) |
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:http://blog.csdn.net/mn960mn/article/details/51352007