自动装配的DAO对象为空Spring Boot

时间:2017-03-15 16:25:20

标签: java mysql spring spring-boot dao

我正在编写一个可以访问数据库的休息服务,以查看,添加和更新mysql表中的字段。我用Spring Boot实现了这个。

事实是,当我尝试自动装配DAO对象时它不起作用,为null,所以我的应用程序总是抛出NullPointerException。

这是我的应用程序类:

@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = "com.setoncios.api")
@EnableJpaRepositories("com.setoncios.api.dao.workers.WorkerDAO.java")
public class GenericApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(GenericApiApplication.class, args);
    }

    @Bean
    public Docket swaggerSettings() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/");
    }

这是我的pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>


</dependencies>

这是我的DAO实现:

@Component
public interface WorkerDAO extends CrudRepository<Persona,String>{

}

包含抛出异常的方法的rest方法:

@RequestMapping(value = "/worker", method = RequestMethod.POST)
public ResponseEntity<?> addWorkerInDatabase(HttpServletRequest request,
        @RequestParam(value = "json", defaultValue = 
        "{\"dni\":\"00000000A\",\"nombre\":\"Paco\",\"apellido1\":\"Ruiz\",\"apellido2\":\"Díaz\"}") final String json){
    ProcessAction object = new AddWorkerInDatabaseAction(request, json);
    return object.createResponse();
}

班级本身:

public class AddWorkerInDatabaseAction extends ProcessAction{
private String json;

@Autowired
private UserDatabase userDb = new UserDatabase();

@Autowired
private WorkerDAO workDb;

public AddWorkerInDatabaseAction(HttpServletRequest request, String json) {
    super(request);
    this.json = json;
}

@Override
protected Object action() throws ExpectedException {
    Persona newWorker = new Gson().fromJson(json, Persona.class);
    Cookie c = findCookie("userdata");
    String[] loggedUser = null;

    if(newWorker == null){
        LOGGER.warning("Unable to decrypt from json to Persona.");

    } else if(c == null){
        LOGGER.info("Couldn't find cookie. Unable to add a worker.");
        newWorker = null;

    } else {            
        try {
            userDb.connect();

            loggedUser = c.getValue().split(":");

            if(!loggedUser[0].equals("00000000A") || !loggedUser[1].equals(userDb.selectPassword("00000000A"))){
                LOGGER.warning("You need privileges to add a worker.");

            } else if(newWorker.getNombre() == null || newWorker.getApellido1() == null || newWorker.getApellido2() == null){
                workDb.save(newWorker); //Here's where the exception is being thrown. 

            } else {
                workDb.save(newWorker); //Here's where the exception is being thrown. 
            }


        } catch (ClassNotFoundException e) {
            userDb.rollback();
            newWorker = null;
            LOGGER.warning("Exception with driver encountered.");
            throw new ExpectedException(1, e.getMessage());

        } catch (SQLException e) {
            userDb.rollback();
            newWorker = null;
            throw new ExpectedException(2, e.getMessage());

        } finally {
            userDb.commit();
            userDb.disconnect();
        }
    }


    return newWorker;
}

}

我已经阅读了很多帖子,但我找不到它的工作方式。有没有我错过写的注释?

提前谢谢:3

编辑。应用答案后,我的主要课程:

@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = "com.setoncios.api")
@EnableJpaRepositories("com.setoncios.api.dao.workers")
public class GenericApiApplication {

public static void main(String[] args) {
    SpringApplication.run(GenericApiApplication.class, args);
}

@Bean
public Docket swaggerSettings() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/");
}

}

其余方法:

@RequestMapping(value = "/worker", method = RequestMethod.POST)
public ResponseEntity<?> addWorkerInDatabase(HttpServletRequest request,
        @RequestParam(value = "json", defaultValue = 
        "{\"dni\":\"00000000A\",\"nombre\":\"Paco\",\"apellido1\":\"Ruiz\",\"apellido2\":\"Díaz\"}") final String json){
    return addDB.createResponse(request, json);
}

AddWorkerInDatabaseAction类:

@Service
public class AddWorkerInDatabaseAction extends ProcessAction{
@Autowired
private UserDatabase userDb = new UserDatabase();

@Autowired
private WorkerDAO workDb;

public AddWorkerInDatabaseAction() {
}

@Override
protected Object action(Object...args) throws ExpectedException {
    Persona newWorker = new Gson().fromJson((String) args[1], Persona.class);
    workDb.save(newWorker);


    return newWorker;
}

}

希望它有所帮助。

2 个答案:

答案 0 :(得分:1)

我想可能是你的注释

@EnableJpaRepositories("com.setoncios.api.dao.workers.WorkerDAO.java")

错了。此批注的默认值是用于扫描带注释的类的基础包。所以在你的情况下它应该是"com.setoncios.api.dao.workers"

您还可以设置basePackageClasses以获得更多类型安全性,然后您可以将其指向WorkerDAO.class

另外,正如另一个答案所示,您应该使AddWorkerInDatabaseAction服务并在您的控制器中自动装配。那样春天会注入必要的豆子。

答案 1 :(得分:1)

您可以将AddWorkerInDatabaseAction类设为Spring Service。而不是将参数传递给构造函数,您可以直接将它们传递给实际的方法。

 @Service
 public class AddWorkerInDatabaseAction extends ProcessAction{
     .....

     protected Object action(HttpServletRequest request, String json) throws ExpectedException {
     .....
 }

在你的控制器中,你可以自动装配spring创建的这个类的bean,

 private class MyController{

     @Autowire
     ProcessAction object;

     @RequestMapping(value = "/worker", method = RequestMethod.POST)
     public ResponseEntity<?> addWorkerInDatabase(HttpServletRequest request,
             @RequestParam(value = "json", defaultValue = 
    "{\"dni\":\"00000000A\",\"nombre\":\"Paco\",\"apellido1\":\"Ruiz\",\"apellido2\":\"Díaz\"}") final String json){
         return object.createResponse(request, json);
 }