![](/img/trans.png)
[英]Spring cannot include/exclude beans using filters of type REGEX with an asterisk in @ComponentScan
[英]Spring @ComponentScan exclude/include filters
作為Spring MVC應用程序中的一個好習慣,Web配置應該只選擇“前端”組件,例如@Controller
或@RestController
。
每個其他bean都應該由Root應用程序上下文選取。
我已經將Web配置定義如下(請記住,我不需要@EnableMvc
注釋,因為它擴展了WebMvcConfigurationSupport
)
@Configuration
@ComponentScan(
basePackages = { ... },
useDefaultFilters = false,
includeFilters = @Filter({
Controller.class,
ControllerAdvice.class}))
而Root的配置如下。
@Configuration
@ComponentScan(
basePackages = { ... },
excludeFilters = @Filter({
Controller.class,
ControllerAdvice.class}))
我已經定義了兩個@RestControllerAdvice
類,第一個捕獲所有通用Exception
,第二個捕獲更具體的ServiceException
。
拋出ServiceException
,永遠不會調用特定的顧問,而只選擇通用的顧問。 兩個配置類中的基礎包都是相同的。
我是否還RestControllerAdvice
在排除和包含過濾器上指定RestControllerAdvice
? 還是我錯過了別的什么?
編輯:
@RestControllerAdvice
都沒有basePackeges
或任何特定條件。 並且實際找到並注冊了ServiceException
。
如果我將異常處理程序移動到工作處理程序而不是它被調用。 這就是我的工作方式。 如果我將ServiceException
處理程序移動到一個單獨的類中,則不再調用它。
@RestControllerAdvice
public class GlobalRestControllerAdviser extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleBindException(
final BindException ex,
final HttpHeaders headers,
final HttpStatus status,
final WebRequest request) {
return new ResponseEntity<Object>(
buildPresentableError(ex.getAllErrors().get(0)),
HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ServiceException.class)
protected Response<?> handleServiceException(final ServiceException e) {
...
}
@ExceptionHandler(Exception.class)
protected ResponseEntity<Object> handleGenericException(final Exception ex) {
...
}
}
似乎最通用的ExceptionHandler
覆蓋了更具體的一個。
幾乎在那里,使用FilterType type
並分離過濾器。
@Configuration
@ComponentScan(
basePackages = { ... },
excludeFilters = {
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=Controller.class),
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=ControllerAdvice.class)
}
)
或者,我建議您創建一個自定義注釋(例如@FrontEnd
)並將過濾器應用於它。
基本上@ControllerAdvice
注釋類是有序的,這意味着如果Spring內部發現一個接受拋出異常的@ExceptionHandler
,它將使用那個並停止。
當有多個類時,可以使用@Order
設置bean優先級(例如)。 使用@Order
注釋包含類的ServiceException
使其正常工作。
此外,根據此功能請求https://jira.spring.io/browse/SPR-8881,我們可以在一個@Filter
注釋上指定多個類,無需將它們拆分為多個@Filter
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.