mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-07-21 15:09:48 +08:00
Add: SpringUtil.getBean(TypeReference<T>)
添加Spring工具类静态方法,通过类型参考(TypeReference)获取带泛型参数的Bean,同时添加了一个小的单元测试
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package cn.hutool.extra.spring;
|
||||
|
||||
import cn.hutool.core.lang.TypeReference;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import lombok.Data;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
@@ -8,6 +10,11 @@ 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)
|
||||
@SpringBootTest(classes = {SpringUtil.class, SpringUtilTest.Demo2.class})
|
||||
//@Import(cn.hutool.extra.spring.SpringUtil.class)
|
||||
@@ -20,6 +27,14 @@ public class SpringUtilTest {
|
||||
Assert.assertEquals("test", testDemo.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getBeanWithTypeReferenceTest() {
|
||||
Map<String, Object> mapBean = SpringUtil.getBean(new TypeReference<Map<String, Object>>() {});
|
||||
Assert.assertNotNull(mapBean);
|
||||
Assert.assertEquals("value1", mapBean.get("key1"));
|
||||
Assert.assertEquals("value2", mapBean.get("key2"));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Demo2{
|
||||
private long id;
|
||||
@@ -32,5 +47,13 @@ public class SpringUtilTest {
|
||||
demo.setName("test");
|
||||
return demo;
|
||||
}
|
||||
|
||||
@Bean(name="mapDemo")
|
||||
public Map<String, Object> generateMap() {
|
||||
HashMap<String, Object> map = MapUtil.newHashMap();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
return map;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user