これは深刻な "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);
}
}
}
また、Mongoをサポートするようにアプリケーションコンテキストを正しく設定していることを確認してください。 '@ EnableMongoRepositories'。 https://github.com/spring-projects/spring-data-mongodb – Ben
ベンに感謝します。またgithubのリンクに感謝します。非常に便利。 – Bloomberg58
あなたは '@Repository'だけを' @ EnableMongoRepositories'する必要はありません。 –