我有多个由 Gradle 管理的 Spring Boot 微服务应用程序。有一个常见的 jar 和特定于域的 jar,其组织方式如下:
| common/
|-- common.jar
| p/
|-- p-ingest.jar
| g/
|-- g-ingest.jar
我的普通jar有一个类,
BaseRESTService
, 自动连线 HttpServletRequest
(我已经知道这是一个坏主意 - 不是我的代码)。 p-ingest.jar 导入 common,g-ingest jar 也是如此。 geoalloc 运行没有问题。但是 p 摄取,这是从 g-ingest 复制而来的,不运行。当上下文尝试初始化时,p-ingest 会出现以下异常:Field request in com.company.common.BaseRESTService required a bean of type 'javax.servlet.http.HttpServletRequest' that could not be found.
我对 Spring 并不陌生,我了解码件扫描和 Autowiring 以及所有这些,但我已经为此工作了 2 天,我不知道发生了什么。我跑了
gradle dependencies
在这两个项目上,树是相同的。下面是 p-ingest 的启动应用类:@SpringBootApplication
@ComponentScan(
basePackageClasses = com.company.common.ConfigurationSearchCriteriaFactory.class,
basePackages = {"com.company.erd"})
@EnableJpaRepositories(basePackages = "com.company.erd")
@EntityScan(basePackages = {"com.company.erd"})
public class PortfolioRiskIngestApplication implements ApplicationRunner {
private static final Log logger = LogFactory.getLog(IngestApplication.class);
@Autowired
private IngestService ingestService;
public PIngestApplication(PIngestService ingestService) {this.ingestService = ingestService;}
public static void main(String[] args) {
SpringProfileHelper.setProfileFromAwsEnvironment();
SpringApplication app = new SpringApplication(PIngestApplication.class);
app.setWebEnvironment(false);
app.run(args);
}
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
@Override
public void run(ApplicationArguments applicationArguments) {
// define the log info
LogInfo info = LogInfo.newInstance("run", new Object[] { StringUtility.arrayToString(applicationArguments.getSourceArgs()) });
// log entry
logger.info(info.entry());
ingestService.run(applicationArguments.getSourceArgs());
// log exit
logger.info(info.exit());
}
}
这是
BaseRestService
的摘录:public class BaseRESTService
{
private static final Log logger = LogFactory.getLog(BaseRESTService.class);
@Autowired
private HttpServletRequest request;
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(value = EntityNotFoundException.class)
public ErrorResponse handleEntityNotFoundException(EntityNotFoundException e){
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setErrorCode(HttpStatus.NOT_FOUND.value());
errorResponse.setErrorMessage(e.getMessage());
logger.error(e.getMessage(), e);
return errorResponse;
}
没什么特别的。所涉及的所有类都非常简单。我欢迎任何人对我做错的任何想法......
最佳答案
我发现了我的问题,这是一个菜鸟错误。出于懒惰,我对整个代码库进行了组件扫描,它选择了我们在公共(public) jar 中的 Controller ,该 jar 仅适用于我们的 REST 应用程序。组件仅扫描实际所需的包有效。
关于java - 无法在多模块 Gradle 应用程序中 Autowiring HttpServletRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331760/