dwightschrute
dwightschrute

Reputation: 33

How to get a CrudRepository instance?

Recently I have been following this guide on how to persist data in a in-memory H2 database using Spring Boot:

In it, one first defines a CustomerEntity class and then a CustomerRepository interface. Then, in the main class, a lot of annotation magic is being done, which enables one to simple "have" a CustomerRepository instance, which can be used to persist data to the database, retrieve it, etc.

This is all fine, however, I need to use such a CustomerRepository instance outside of the main class, inside another class. Since the tutorial does not reveal the magic that was done to make it available in the main class, I do not know how to make it happen in the class that I need it in.

I have been trying to figure this out almost all day long, but I just get lost inside a jungle of articles all trying to explain which Spring annotation does what, and I am really exhausted now.

I want to do something like this:

public class Foo {

  private CustomerRepository repo;

  // ...

  public void storeCustomer(String firstName, String lastName) {
    this.repository.save(new Customer(firstName, lastName));
  }

}

I would be very happy about some hints.

Upvotes: 3

Views: 1762

Answers (2)

Chanky Mallick
Chanky Mallick

Reputation: 587

You need to autowire CustomerRepository object and also need to autowire Foo object foo object from your controller.

public class Foo {

@Autowire
private CustomerRepository repo;

  public void storeCustomer(String firstName, String lastName) {
  this.repo.save(new Customer(firstName, lastName));
  } 
}

And u need to autowire the Foo object from controller/restcontroller to call storeCustomer method.

@Controller
public class CustomerController{

  @Autowired
  Foo obj;
  @RequestMapping(method=RequestMethod.GET,value="addNewCustomer")
   public String addnewCustomer(){      
      obj.storeCustomer("firstname","lastname");
      return "";

   }
}

And define your autowired beans in any class using @Configuration

@Configuration
public class AppConfig {
  @Bean
  public Foo obj(){
      return new Foo();
  }
  @Bean
  public CustomerRepository repo(){
      return new CustomerRepository();
  }
}

Upvotes: 2

Daniel C.
Daniel C.

Reputation: 46

Here is one example

@Component
public class Foo{

  @Autowired
    private CustomerRepository repo;

  // ...

  public void storeCustomer(String firstName, String lastName) {
    this.repository.save(new Customer(firstName, lastName));
  }

}

If you need to try it, you can use a 'CommandLineRunner'

@Bean
public CommandLineRunner myRunner(Foo myFooService){

  myFooService.storeCustomer("name","lastname");

}

Upvotes: 0

Related Questions