2017-03-15 24 views
0

私は、データベースにアクセスしてmysqlテーブルのフィールドを表示、追加、更新することができるレストサービスをプログラミングしています。私はこれをSpring Bootで実装しました。Autowired DAOオブジェクトがnullです。Springブート

実際、私はDAOオブジェクトをautowireしようとすると動作しません。これは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>{ 

} 

含まれている残りの方法例外をスローするメソッド:

@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; 
} 

} 

は、それが誰かに役立ちます願っています。

+0

を春が作成し、このクラスのBeanをautowireすることができますが、 'new'演算子で' AddWorkerInDatabaseAction'クラスのオブジェクトを作成しないでください、あなたはそれをautowire必要があります代わりに。 –

+0

ProcessActionからのアクションが増えたので、私はそうしました。そうして私はそれらを区別しようとしました。私はこれを改善する他の方法を見つけることを試みる。 –

答えて

1

AddWorkerInDatabaseActionクラスをSpringサービスにすることができます。また、引数をコンストラクタに渡す代わりに、それらを実際のメソッドに直接渡すこともできます。お使いのコントローラで

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

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

、あなたは、

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); 
} 
+1

ありがとうございました、最終的に解決するには配線がさらに必要になったようです。郵便番号で私の投稿を編集します。 –

1

私はおそらくあなたの注釈

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

が間違っていると思います。この注釈のデフォルト値は、注釈付きクラスをスキャンする基本パッケージです。あなたのケースでは、それは"com.setoncios.api.dao.workers"でなければなりません。

あなたはより多くの型の安全性を得るために設定することができ、他の答えはあなたがAddWorkerInDatabaseActionサービスとautowireあなたのコントローラでこれを行う必要があります示唆するように、あなたはちょうどまたWorkerDAO.class

にそれを指すことができbasePackageClassesもあります。そうすれば、春に必要な豆が注入されます。

+0

アノテーションの変更も間違っていました。パッケージに通知する必要があります。 "com.setoncios.api.dao.workers"に変更するとうまくいきました。 –

関連する問題