SpringBoot使用JdbcTemplate

项目结构

project

pom.xml中添加依赖

    
      mysql
      mysql-connector-java
      5.1.21
    

    
      org.springframework.boot
      spring-boot-starter-jdbc
    

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/book_manager
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

UserService.java

package com.inverseli.learning.service;   
/**  
 * @date:2018年9月22日 下午11:46:02    
 * @author liyuhao
 * @version 1.0   
 * @since JDK 1.8  
 * @description:  
 */
public interface UserService {
    /**
     * @author liyuhao
     * @date 2018年9月22日 下午11:47:28
     * @param name
     * @param age void
     * @description:
     */
    void create(String name,Integer age);
    /**
     * @author liyuhao
     * @date 2018年9月22日 下午11:48:02
     * @param name void
     * @description:
     */
    void deleteByName(String name);
    /**
     * @author liyuhao
     * @date 2018年9月22日 下午11:48:38
     * @return Integer
     * @description: 获得用户总数
     */
    Integer getAllUsers();
    /**
     * @author liyuhao
     * @date 2018年9月22日 下午11:48:59 void
     * @description:
     */
    void deleteAllUser();
}
  

UserServiceImpl.java

package com.inverseli.learning.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.inverseli.learning.service.UserService;

/**  
 * @date:2018年9月22日 下午11:46:53    
 * @author liyuhao
 * @version 1.0   
 * @since JDK 1.8  
 * @description:  
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private JdbcTemplate jdbcTemplate; 
    
    @Override
    public void create(String name, Integer age) {
        jdbcTemplate.update("insert into USER(NAME,AGE) values (?,?)",name,age);
    }

    @Override
    public void deleteByName(String name) {
        jdbcTemplate.update("delete from USER where NAME = ?",name);
    }

    @Override
    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    @Override
    public void deleteAllUser() {
        jdbcTemplate.update("delete from USER");
    }

}
ApplicationTest.java
package com.inverseli.learning;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.inverseli.learning.service.UserService;


/**  
 * @date:2018年9月22日 下午11:55:03    
 * @author liyuhao
 * @version 1.0   
 * @since JDK 1.8  
 * @description:  
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HelloApplication.class)
public class ApplicationTest {

    @Autowired
    private UserService userService;
    @Before
    public void setUp() {
        userService.deleteAllUser();
    }
    
    @Test
    public void test() {
        userService.create("a", 1);
        userService.create("b", 2);
        userService.create("c", 3);
        userService.create("d", 4);
        userService.create("e", 5);
        
            
        
        // 删除两个用户
        userService.deleteByName("a");
        userService.deleteByName("e");

        // 查数据库,应该有5个用户
    }
}

踩过的坑

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.inverseli.learning.ApplicationTest': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.inverseli.learning.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:400)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:242)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.inverseli.learning.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
    ... 28 more

这个错误大致就是说注入UserService失败,检查了注解@Service标注在接口实现类上没错,注入的是UserService也没错,最有可能的原因就是没有扫描到我的实现类所在的包。
就是少了下面的这个注解导致的问题

@SpringBootTest(classes = HelloApplication.class)

按照我现在的理解,就是说标明了SpingBoot的启动类的位置,而SpringBoot是自动扫描启动类所在包的同级目录和子目录的所以就扫描到了需要的包,就解决了这个问题,我不知道这么理解有没有问题。

你可能感兴趣的:(SpringBoot使用JdbcTemplate)