【发布时间】:2020-03-24 19:34:02
【问题描述】:
我正在尝试将我的控制器连接到其中一个 spring 应用程序中的存储库,但我收到一条错误消息,提示“TweetsController.TweetsController 中的字段 tweetRepository 需要一个无法找到的 'TweetsController.TweetRepository' 类型的 bean。 "
有人可以帮我解决这个问题吗?提前致谢。我也附上了代码示例。
TwitterApplication.java
package SpringMVC.Twitter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan("AuthController")
@ComponentScan("TweetsController")
public class TwitterApplication {
public static void main(String[] args) {
SpringApplication.run(TwitterApplication.class, args);
}
}
TwitterController.java
package TweetsController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
public class TweetsController {
@Autowired
private TweetRepository tweetRepository;
@RequestMapping("/tweets")
public Iterable<TweetsContent> getAllTweets() {
return tweetRepository.findAll();
}
@RequestMapping("tweet/{id}")
public Optional<TweetsContent> getTweet(@PathVariable int id) {
return tweetRepository.findById(id);
}
@RequestMapping(method = RequestMethod.POST, value = "/tweets")
public boolean addTweet(@RequestBody TweetsContent tweet) {
TweetsContent t = tweetRepository.save(new TweetsContent(tweet.getTitle(), tweet.getContent()));
if (t != null)
return true;
else
return false;
}
}
TwitterRepository.java
package TweetsController;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TweetRepository extends CrudRepository<TweetsContent, Integer> { }
【问题讨论】:
-
类路径中有spring-data-jpa吗?
-
@SurajGautam:我没有得到你的问题。这是我第一次接触 Spring,所以为愚蠢的后续行动道歉。询问我是否在 pom.xml 文件中添加了 spring-data-jpa?
-
好的,在上面的代码中,你能把包也放上去吗?我认为您在扫描时遇到了问题。
-
@SurajGautam 编辑了代码以显示我的包。
-
我建议遵循 Spring Boot 参考指南中提到的最佳实践。将您的存储库和控制器移动到与您的
TwitterApplication相同的包中或其子包中。然后删除@CompoentScan,它将起作用。否则,您需要为包含 repos 的包添加@EnableJpaRepositories。但是,如果不遵循建议格式,您会失去一些好处。
标签: java mysql spring spring-boot spring-mvc