我是靠谱客的博主 清脆大山,这篇文章主要介绍SpringBoot动态创建Bean,现在分享给大家,希望可以做个参考。

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
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)

最后

以上就是清脆大山最近收集整理的关于SpringBoot动态创建Bean的全部内容,更多相关SpringBoot动态创建Bean内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部