这是 TopicService.java 的一部分
我在这一行得到一个 NULL 指针异常 TopicRepo.findAll().forEach(topics::add);
私有主题Repo TopicRepo;这是我自动连接依赖项的地方
package io.javabrains.example.topic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class TopicService {// creating a business service
@Autowired
private topicRepo TopicRepo; // whenever the TopicService creates an instance then the instance of topicRepo will be injectjed in the variable
private ArrayList<Topic> topics = new ArrayList<>(Arrays.asList(
new Topic("spring1", "nishhcal", "name"),
new Topic("spring2", "nishhca2", "name2"),
new Topic("spring3", "nishhca3", "name3")));
public List<Topic> getAllTopics(){
// return topics;
List<Topic> topics = new ArrayList<>();
TopicRepo.findAll().forEach(topics::add);
return topics;
}
public Topic getSpecificTopic(String id){
// for (int r=0; r < topics.size(); r++){
//
// if((topics.get(r).getId()).equals(id)){
//
// return topics.get(r);
// }
// }
// return topics.stream().filter(t -> t.getId().equals(id)).findFirst().get();// alternative way of doing it
return topics.get(0);
}
public void addTopic(Topic topic){
// topics.add(topic);
TopicRepo.save(topic);
}
topicRepo.java,这是我扩展 crud 存储库的地方
package io.javabrains.example.topic;
import org.springframework.data.repository.CrudRepository;
public interface topicRepo extends CrudRepository<Topic, String> {
}
这就是我的 application.properties 文件中的内容
#JPA
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=default
spring.jpa.show-sql=true
这是我的 Topic.java 的一部分
package io.javabrains.example.topic;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Topic {
@Id
private String id;
private String name;
private String description;
public Topic() {
}