mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
commit
9d7888acd1
@ -4,6 +4,7 @@ import cn.hutool.core.lang.TypeReference;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@ -148,6 +149,22 @@ public class SpringUtil implements ApplicationContextAware {
|
||||
final String[] activeProfiles = getActiveProfiles();
|
||||
return ArrayUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态向Spring注册Bean
|
||||
* <p>
|
||||
* 由{@link org.springframework.beans.factory.BeanFactory} 实现,通过工具开放API
|
||||
*
|
||||
* @param beanName 名称
|
||||
* @param bean bean
|
||||
* @param <T> 泛型
|
||||
* @author shadow
|
||||
* @date 2020-09-04
|
||||
*/
|
||||
public static <T> void registerBean(String beanName, T bean) {
|
||||
ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
|
||||
context.getBeanFactory().registerSingleton(beanName, bean);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -10,7 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ -18,6 +20,27 @@ import java.util.Map;
|
||||
//@Import(cn.hutool.extra.spring.SpringUtil.class)
|
||||
public class SpringUtilTest {
|
||||
|
||||
/**
|
||||
* 注册bean
|
||||
* 方便执行顺序使用abcd...的顺序命名方法
|
||||
*/
|
||||
@Test
|
||||
public void a() {
|
||||
Demo2 registerBean = new Demo2();
|
||||
registerBean.setId(123);
|
||||
registerBean.setName("222");
|
||||
SpringUtil.registerBean("registerBean", registerBean);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证注册的bean
|
||||
*/
|
||||
@Test
|
||||
public void b() {
|
||||
Demo2 registerBean = SpringUtil.getBean("registerBean");
|
||||
Assert.assertEquals(123, registerBean.getId());
|
||||
Assert.assertEquals("222", registerBean.getName());
|
||||
}
|
||||
@Test
|
||||
public void getBeanTest(){
|
||||
final Demo2 testDemo = SpringUtil.getBean("testDemo");
|
||||
|
Loading…
x
Reference in New Issue
Block a user