Spring Boot + Mybatis + Spring MVC環境配置(四):MVC框架搭建

hky87發表於2018-08-18

一、 建立service、serviceImpl、controller包,建立完之後的專案結構如下:


二、編寫UserService和UserServiceImpl

UserService.java

package com.kai.demo.service;
import com.kai.demo.model.User;
public interface UserService {
	public String show();
	User selectByPrimaryKey(Integer id);
}

UserServiceImpl.java

package com.kai.demo.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kai.demo.dao.UserMapper;
import com.kai.demo.model.User;
import com.kai.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	@Override
	public String show() {
		return "test service";
	}
	@Override
	public User selectByPrimaryKey(Integer id) {
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(id);
	}
}


三、UserController.java

package com.kai.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kai.demo.service.UserService;
@RestController
public class UserController {
	
	@Autowired
	private UserService userService;	
	@RequestMapping(value = "/show")  
    public String show(){
       return userService.show();
		}
	
	@RequestMapping("/getUser")
	public String getUser() {
		return userService.selectByPrimaryKey(1).toString();
    }
	
}


四、對UserController進行單元測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTests {
	@Autowired
	private WebApplicationContext context;
	private MockMvc mvc;
	@Before
	public void setUp() throws Exception {
		mvc=MockMvcBuilders.webAppContextSetup(context).build();
	}
	
    @Test
    public void show() throws Exception{
    	mvc.perform(MockMvcRequestBuilders.get("/show").accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andDo(MockMvcResultHandlers.print())
        .andReturn();
    }
	
	 @Test
	    public void getUser() throws Exception {
		 mvc.perform(MockMvcRequestBuilders.get("/getUser")
	                .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(MockMvcResultHandlers.print());
	    }
	
	
}

結果:


完整環境下載地址: https://github.com/CatherineHu/Spring-Boot-Mybatis-MVC  


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10314474/viewspace-2200333/,如需轉載,請註明出處,否則將追究法律責任。

相關文章