spring boot版本1.4.0
JDK1.8
代码如下:
package com.qq.spring.boot.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Integer addBook(String name){
String sql = "insert into books (bname)values('"+name+"')";
return jdbcTemplate.update(sql);
}
}
package com.qq.spring.boot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qq.spring.boot.dao.BookDao;
@RestController
public class BookController {
@Autowired
private BookDao bookDao;
@GetMapping("/book/home")
public String home(){
System.out.println("xxxxxxxxxxxxxhomexxxxxxxxxx");
bookDao.addBook("home");
return "bookhome";
}
}
test代码如下:
package com.qq.spring.boot.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
public class BookControllerTest2 {
@Autowired
private MockMvc mvc;
@Test
public void testHome() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/book/home"))
.andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().string("bookhome"));
}
}
现在的问题是这样的,正常跑,可以访问/book/homeurl,没有问题
但是,跑junit test的时候,报错,
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.qq.spring.boot.dao.BookDao] found for dependency [com.qq.spring.boot.dao.BookDao]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我的spring容器中,是有BookDao这个bean的,为啥还是报错?