我有多个由Gradle管理的Spring Boot微服务应用程序。有一个通用的jar和特定于域的jar,其组织方式如下:
| common/
|-- common.jar
| portrisk/
|-- portrisk-ingest.jar
| geoalloc/
|-- geoalloc-ingest.jar
我的普通jar有一个BaseRESTService
类,可以自动连接HttpServletRequest
(我已经知道这是一个坏主意-不是我的代码)。 portrisk-ingest.jar导入common,geoalloc-ingest jar也导入。 geoalloc运行没有问题。但是,实际上从geoalloc复制的 portrisk 无法运行。当上下文尝试初始化时,portrisk会收到以下异常:
Field request in com.trp.erd.common.BaseRESTService required a bean of type 'javax.servlet.http.HttpServletRequest' that could not be found.
我对Spring并不陌生,并且我了解组件扫描和自动装配以及所有其他方面,但是我已经进行了2天的工作,我无法知道发生了什么。我在两个项目上都运行了gradle dependencies
,并且树是相同的。下面是portrisk的启动应用程序类:
@SpringBootApplication
@ComponentScan(
basePackageClasses = com.trp.erd.common.ConfigurationSearchCriteriaFactory.class,
basePackages = {"com.trp.erd"})
@EnableJpaRepositories(basePackages = "com.trp.erd")
@EntityScan(basePackages = {"com.trp.erd"})
public class PortfolioRiskIngestApplication implements ApplicationRunner {
private static final Log logger = LogFactory.getLog(PortfolioRiskIngestApplication.class);
@Autowired
private PortfolioRiskIngestService ingestService;
public PortfolioRiskIngestApplication(PortfolioRiskIngestService ingestService) {this.ingestService = ingestService;}
public static void main(String[] args) {
SpringProfileHelper.setProfileFromAwsEnvironment();
SpringApplication app = new SpringApplication(PortfolioRiskIngestApplication.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;
}
没什么特别的。涉及的所有类都非常简单。我欢迎任何人对我做错的任何想法...
答案 0 :(得分:2)
我发现了我的问题,那是一个菜鸟的错误。出于懒惰,我对整个代码库进行了组件扫描,从而选择了我们在普通jar中仅用于REST应用程序的控制器。组件仅扫描实际需要的软件包。
答案 1 :(得分:1)
您可以使用RequestContext来获得HttpServletRequest
@Inject
private RequestContext requestContext;
并在方法中调用getRequest():
HttpServletRequest request = requestContext.getRequest();