接下來我們來編寫一個(gè)測試接口柱蟀,測試整個(gè)項(xiàng)目能否成功運(yùn)行
首先我們在數(shù)據(jù)庫的“user”表中增加一條記錄变骡,作為測試使用马僻;
這里我們做這樣一個(gè)測試,編寫一個(gè)方法去通過userid,去查詢用戶的信息癞尚,并且將信息返回到頁面
逆向工程中已經(jīng)為我們提供了selectUserByPrimarykey()的方法,所以只要調(diào)用此方法就可以乱陡。
現(xiàn)在我們在ycshop-manager-interfaces模塊創(chuàng)建包c(diǎn)n.yuechenc.ycshop.manager.interfaces;
在此包里面創(chuàng)建接口:
package cn.yuechenc.ycshop.manager.interfaces;
import cn.yuechenc.pojo.User;
public interface UserService {
public User selectUserByPrimarykey(String userid);
}
然后在ycshop-manager-service模塊下創(chuàng)建包c(diǎn)n.yuechenc.ycshop.manager.service.impl
在此包里創(chuàng)建UserServiceImpl實(shí)現(xiàn)了浇揩,實(shí)現(xiàn)UserService接口
package cn.yuechenc.ycshop.manager.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.yuechenc.manager.dao.mapper.UserMapper;
import cn.yuechenc.pojo.User;
import cn.yuechenc.ycshop.manager.interfaces.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectUserByPrimarykey(String userid) {
return userMapper.selectByPrimaryKey(userid);
}
}
此時(shí)我們的service層就算完成了,接下來憨颠,我們對修改過得項(xiàng)目進(jìn)行install,
此時(shí)我們會(huì)發(fā)現(xiàn)胳徽,在對ycshop-manager進(jìn)行install的時(shí)候回報(bào)一個(gè)錯(cuò)积锅,如圖:
此處請參考下面的解決方法:
Maven Install報(bào)錯(cuò):Perhaps you are running on a JRE rather than a JDK?
解決之后,對ycshop-manager工程進(jìn)行build,看到下圖养盗,表示已經(jīng)成功將接口暴露到dubbo服務(wù)了
下面缚陷,我們就需要在ycshop-manager-web工程中去接收測試能否獲取到接口服務(wù)
編寫controller
在web模塊下編寫UserController
package cn.yuechenc.ycshop.manager.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.yuechenc.pojo.User;
import cn.yuechenc.ycshop.manager.interfaces.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUser")
@ResponseBody
private User getUser(){
return userService.selectUserByPrimarykey("1a");
}
}
此處在注入service是會(huì)注入不進(jìn)來,是因?yàn)橹按罱üこ淌菦]有在web工程的pom文件中加入對接口的依賴往核,補(bǔ)充:
<!-- 對 dao 的依賴 -->
<dependency>
<groupId>cn.yuechenc</groupId>
<artifactId>ycshop-manager-dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!-- 對接口的依賴 -->
<dependency>
<groupId>cn.yuechenc</groupId>
<artifactId>ycshop-manager-interfaces</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
現(xiàn)在保持依次[build]
ycshop-manager
和ycshop-manager-web
在瀏覽器輸入http://localhost:8080/user/getUser進(jìn)行訪問箫爷,報(bào)如圖錯(cuò)誤
是因?yàn)閐ubbo服務(wù)之間通行時(shí)會(huì)將信息序列化之后以流的形式傳輸,所以就要求傳輸?shù)膶ο笫强梢孕蛄谢哪羧澹颂幹恍枳屛覀兊膒ojo類實(shí)現(xiàn)Serializable接口即可
在此install項(xiàng)目并運(yùn)行虎锚,并且訪問http://localhost:8080/user/getUser
可以在瀏覽器中看到如下信息
到這里,我們所有的后臺(tái)項(xiàng)目環(huán)境就算是搭建好了薄货,接下來就是業(yè)務(wù)邏輯的開發(fā)
我們下節(jié)見翁都。