我已经使用JPA使用Spring Boot创建了基本应用程序。我在RatingResource中为RatingRepo添加了@AutoWired批注,但没有向RatingRepo添加@Component批注
package com.example.demo;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.RatingsRateService.model.Rating;
import com.example.demo.RatingsRateService.model.UserRating;
@RestController
@RequestMapping("ratingsdata")
public class RatingResource {
@Autowired
RatingRepo repo;
/*
* @RequestMapping("/{movieId}") public Rating
* getRating(@PathVariable("movieId") String movieId) { return new
* Rating(movieId,7); }
*/
@RequestMapping("users/{userid}")
public UserRating getRating(@PathVariable("userid") int userid) {
List<Rating> ratings =repo.findByUserId(userid);
/*
* List<Rating> ratings = Arrays.asList(new Rating("1",4), new Rating("2",3),
* new Rating("3",2));
*/
System.out.println(ratings);
UserRating userRating = new UserRating();
userRating.setUserRating(ratings);
return userRating;
}
}
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.example.demo.RatingsRateService.model.Rating;
//to update the data in database , created the interd=face and will implement
//class,primary key
public interface RatingRepo extends JpaRepository<Rating, Integer>{
@Query(" from Rating where userid = ?1")
List<Rating> findByUserId( int userid);
}
。尽管如此,它仍然运行良好。有人可以解释为什么吗?还是不需要为回购添加@Component批注?
答案 0 :(得分:1)
首先需要@Repository注释,而不是@Component
由于以下原因,和@Repository也会自动配置:
可能您正在使用弹簧靴
Spring数据存储库通常从Repository或CrudRepository接口扩展。如果您使用的是自动配置,则会从包含您的主要配置类(用@EnableAutoConfiguration或@SpringBootApplication注释的类)的包中搜索存储库。