Vinay Vishwkarma
Vinay Vishwkarma

Reputation: 27

Can interface without implementation be autowired in service class in spring boot

I watched a spring tutorial video on youtube here in which he did not implemented public interface TopicRepository extends CrudRepository<Topic, String> still he was able to run the application by writing

@Autowired
private TopicRepository topicRepository;

in service class, but when I try the same I get an error like:

Field topicRepository in io.spring.springbootstarter.topic.TopicService required a bean of type 'io.spring.springbootstarter.topic.TopicRepository' that could not be found.

The injection point has the following annotations:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'io.spring.springbootstarter.topic.TopicRepository' in your configuration.

I am new to spring and i am using spring 2.3.1

package io.spring.springbootstarter.topic;

import org.springframework.data.repository.CrudRepository;

public interface TopicRepository extends CrudRepository<Topic, String>{


   //getTopics()
   //getTopic(String id)
  //deleteTopic(String id)
  //updateTopic(Topic t)

}

in below class i am creating object

package io.spring.springbootstarter.topic;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TopicService {


@Autowired
private TopicRepository topicRepository;

public List<Topic> getAllTopics(){
    
    List<Topic> topics=new ArrayList<Topic>();
    topicRepository.findAll().forEach(topics::add);
     return topics;
}

public Optional<Topic> getTopic(String id) {
    
    return topicRepository.findById(id);
}


public void addTopic(Topic topic) {
    topicRepository.save(topic);
    
}

public void updateTopic(String id , Topic topic) {
    topicRepository.save(topic);
    
    
}

public void deleteTopic(String id) {
    topicRepository.deleteById(id);
    
    
    
    }


  }

Upvotes: 0

Views: 1532

Answers (1)

Turing85
Turing85

Reputation: 20185

Interfaces extending CrudRepository are implemented (auto-generated) by Spring by using the Spring Expression Language. The auto-generated classes are spring-beans and thus can be autowired.

You can find more information about Spring Data Repositories in the Official Spring Documentation.

Upvotes: 3

Related Questions