【2019-03-10】个人记录【Maven引入本地依赖 + RestTemplate问题】

2019-03-10
第一: Maven引用本地项目类的方式:

  1. 将需要引入的项目使用maven打包(jar包): 项目根目录cmd: mvn clean package
  2. 在接收项目的pom中复制上述jar包pom内部的 groupId, artifactId 以及 version ,并指定scope为system
  3. 找到打包好的jar包,拷贝其在硬盘内的绝对路径+jar包名称.jar
  4. 在接收项目的pom中指定systemPath为上述路径
  5. 在代码中import即可

如:

	<dependency>
		<groupId>com.starry</groupId>
		<artifactId>data</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<scope>system</scope>
		<systemPath>F:\Starry\data\target\data-0.0.1-SNAPSHOT.jar</systemPath>
	</dependency>

需要注意的是如果 被引入的项目 是springboot项目,则要注意其pom中是否存在

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

若存在则将其注释掉再打包,否则其会生成可直接执行的jar包,无法在引用者代码中使用 import 引入。

第二: springcloud项目中使用RestTemplate的问题:
在使用 RestTemplate 的 getForEntity()(或 getForObject())方法的时候,如果遇到需要将 RestTemplate 返回的结果变为 List 类型的时候,如下代码:

	@AutoWired
	RestTemplate restTemplate;
	...
	ResponseEntity<List> responseEntity =  restTemplate.getForEntity("http://Your-Service-Name/Your-Api", List.class);
	List<User> userList = responseEntity.getBody();

则不会报错,但是一旦使用循环语句去循环这条生成的List的时候,会报异常:

java.util.LinkedHashMap cannot be cast to ‘XXX’

这是由于RestTemplate返回的数据确切地来讲,并不是一个List< T >,而是一个List< HashMap< T , T >>

解决的方法是先将RestTemplate返回的实体使用数组来接收,再将其转换成Json,再将此Json对象转换为List,例如:

	import com.google.gson.Gson;
	import com.google.gson.reflect.TypeToken;
	
	... ...
	
	ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://Your-Service-Name/Your-Api", User[].class);
	User[] users = responseEntity.getBody();
	// 第一个参数是users转换后的json对象, 第二个参数是将这个json对象转换成List< User > 类型
	List<User> list = new Gson().fromJson(new Gson().toJson(users),  new TypeToken<List<User>>(){}.getType());

或 getForObject 方法:

	User[] users = restTemplate.getForObject("http://Your-Service-Name/Your-Api", User[].class);
	List<User> list = new Gson().fromJson(new Gson().toJson(users),  new TypeToken<List<User>>(){}.getType());
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值