在学习SpringBoot的时候,引入jdbcTemplate时出了一点错误
Field jdbcTemplate in com.hsy.service.UserServiceImpl required a bean of type 'org.springframework.jdbc.core.JdbcTemplate' that could not be found.
在网上找了很多资料,最终发现了错误所在之处,原来是在做测试的时候因为使用了@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
自动化配置,所以我们取消了自动化配置,于是程序顺利运行。
测试代码如下
controller层
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/createUser")
public String createUser(int id,int age){
userService.create(id, age);
return "success";
}
}
service层
public interface UserService {
void create(int id,int age);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void create(int id, int age) {
jdbcTemplate.update("insert into testuser(id,age) value (?,?)",id,age);
}
}
application.properties配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名
spring.datasource.username=root
spring.datasource.password=111111
pom.xml配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
最终结果