2019-03-10
第一: Maven引用本地项目类的方式:
- 将需要引入的项目使用maven打包(jar包): 项目根目录cmd: mvn clean package
- 在接收项目的pom中复制上述jar包pom内部的 groupId, artifactId 以及 version ,并指定scope为system
- 找到打包好的jar包,拷贝其在硬盘内的绝对路径+jar包名称.jar
- 在接收项目的pom中指定systemPath为上述路径
- 在代码中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());