![](/img/trans.png)
[英]Spring boot component scan does not recognize qualifier annotation for different beans
[英]Spring boot - beans configuration without @component annotation
作為我大學項目的一部分,我被要求實現一個簡單的 spring-boot 應用程序(僅限后端),它可以通過 HTTP 請求與 Postman 通信。
該項目內置控制器-服務-存儲庫架構,僅包含 1 個實體(帶有字符串內容的 Post 對象)和 2 個端點(創建新帖子,獲取所有帖子)。
我知道有幾種方法可以在 spring-boot 中配置 bean:
第 3 種方式工作得很好,但我被要求實施第二種方式,我真的很難讓它發揮作用。
我越來越:
ServletException: Circular view path [post]: 將再次分派回當前處理程序 URL [/post]。 檢查您的 ViewResolver 設置!
試圖探索這個異常,我確實通過添加這個 maven 依賴來“解決”它:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.2</version>
</dependency>
這導致:
"org.thymeleaf.exceptions.TemplateInputException: Error resolving template [post], template might not exist or might not be accessible by any of the configured Template Resolvers"
我究竟做錯了什么 ?
配置類:
@Configuration
@EnableJpaRepositories(basePackages = {
"com.example.microblog.post.domain.repository"
})
public class ApplicationBeans {
@Bean
public PostController postController(PostService postService){
return new PostController(postService);
}
@Bean
public PostService postService(){
return new PostService();
}
}
控制器類:
@AllArgsConstructor
@RequestMapping(path = "post")
public class PostController {
@Autowired
private PostService service;
@CrossOrigin(origins = "http://localhost:4200")
@PostMapping("")
public PostEntity create(@RequestBody PostDto dto) {
return service.create(dto);
}
@GetMapping("/all")
@CrossOrigin(origins = "http://localhost:4200")
public List<PostEntity> getAll() {
return service.getAll();
}
}
服務等級:
@Transactional
public class PostService {
@Autowired
private PostRepository PostRepository;
public PostEntity create(PostDto dto){
PostEntity newPost = new PostEntity(dto.getContent());
return PostRepository.save(newPost);
}
public List<PostEntity> getAll(){
return PostRepository.findAll();
}
存儲庫類:
public interface PostRepository extends JpaRepository<PostEntity,Long> {}
對於第二種方法,當您創建 Bean 時,盡量不要在為其創建 Bean 的類上使用 @Component/@Controller ...
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
您可以像第三種方法一樣繼續自動裝配它們,盡量不要保留同名的 bean
您的錯誤指向一個方向,即您的控制器難以將您的服務的答案解析為有效的 JSON 響應。
請注意,@RestController 只是添加 @Controller 和 @ResponseBody 注釋的便捷方式。 當您只添加@Bean 注釋時,您不會添加@Controller 或@ResponseBody。 如果您想在不使用這些注解的情況下使用 Controller 類,您需要實現這些類提供的功能。
但是,我真的看不出,為什么將選項 2 用於 Controller 類。 如果您想將它用於@Service 類(與@Component 的作用相同),您可以使用 Ravi 建議的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.