Controller.Controller中的错误字段存储库需要找不到类型为“ Controller.Repository”的bean

时间:2019-11-29 07:51:41

标签: java mysql spring spring-boot spring-mvc

我正在尝试在其中一个Spring应用程序中将我的Controller连接到存储库,但是却收到一条错误消息,提示“ TweetsController.TweetsController中的Field 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> { }

4 个答案:

答案 0 :(得分:0)

在pom上添加spring数据依赖项:

min

答案 1 :(得分:0)

也添加此内容。 @ComponentScan(“ TweetRepository”)

答案 2 :(得分:0)

您不需要使用@ComponentScan(“ AuthController”)和@ComponentScan(“ TweetsController”),因为如果使用@SpringBootApplication,则会从声明此注释的类的包中进行扫描。但是您需要这样放置TwitterApplication:
https://hyperledger-fabric.readthedocs.io/en/release-1.4/channel_update_tutorial.html#generate-the-org3-crypto-material

答案 3 :(得分:0)

您不必在@ComponentScan中指定TwitterApplication,因为spring boot应用程序在启动时会扫描其自己的目录。并删除@Repository 来自存储库类的注释,也不需要它。