2017-08-22 14 views
1

これは深刻な "Springers"の質問です...MongoRepositoryインターフェイスをインスタンス化するには、スプリングブートで@Autowiredをspring mvcに実装する方法はありますか?

私はMongoRepositoryを使いたいです。だから私はspring.io website tutorial for MongoDB CRUD operationsに行きました。

最初の問題は、彼らがSpringブートを使用していることです。 2番目の問題は、インターフェイス上で@Autowiredを使用していることです。そのアノテーションは、オブジェクトを作成することができるように思われます(メソッドは後で呼び出されます)。

だから私は通常の春のMVCと@Autowiredを使用していません。

@Autowiredなしで私はどのように私のregulartスプリングmvcでそのMongoRepositoryインターフェイスを "インスタンス化"できますか?

はMongoRepositoryは

package hello; 

import java.util.List; 

import org.springframework.data.mongodb.repository.MongoRepository; 

public interface CustomerRepository extends MongoRepository<Customer, String> { 

    public Customer findByFirstName(String firstName); 
    public List<Customer> findByLastName(String lastName); 

} 

あなたが@RepositoryであなたのRepositoryクラスに注釈を付けると、それはSpringのコンポーネントスキャンによってピックアップされていていることを確認する必要があります@Autowired

package hello; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.CommandLineRunner; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 

@SpringBootApplication 
public class Application implements CommandLineRunner { 

    @Autowired 
    private CustomerRepository repository; 

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

    @Override 
    public void run(String... args) throws Exception { 

     repository.deleteAll(); 

     // save a couple of customers 
     repository.save(new Customer("Alice", "Smith")); 
     repository.save(new Customer("Bob", "Smith")); 

     // fetch all customers 
     System.out.println("Customers found with findAll():"); 
     System.out.println("-------------------------------"); 
     for (Customer customer : repository.findAll()) { 
      System.out.println(customer); 
     } 
     System.out.println(); 

     // fetch an individual customer 
     System.out.println("Customer found with findByFirstName('Alice'):"); 
     System.out.println("--------------------------------"); 
     System.out.println(repository.findByFirstName("Alice")); 

     System.out.println("Customers found with findByLastName('Smith'):"); 
     System.out.println("--------------------------------"); 
     for (Customer customer : repository.findByLastName("Smith")) { 
      System.out.println(customer); 
     } 

    } 

} 

答えて

2

を含むクラスをインターフェイスを拡張しました。その後、必要に応じて@Autowireをクラスに追加することができます。

クリアするにはインターフェイスを「インスタンス化」しないでください。そのインターフェイスの実装に依存することを宣言します(@Autowired経由)。そしてSpringデータMongDBがクラスパス上にあると仮定します。Springは実行時実装を作成し、注入するBeanとして利用可能にします。

+0

また、Mongoをサポートするようにアプリケーションコンテキストを正しく設定していることを確認してください。 '@ EnableMongoRepositories'。 https://github.com/spring-projects/spring-data-mongodb – Ben

+0

ベンに感謝します。またgithubのリンクに感謝します。非常に便利。 – Bloomberg58

+1

あなたは '@Repository'だけを' @ EnableMongoRepositories'する必要はありません。 –

関連する問題