当已经加载了基于xml的springmvc时,扫描新的手动添加的控制器



我正在进行一个项目,我们正在使用springmvc作为web框架。它有一个基于xml的配置,并首先启动。但我也有插件,我可以手动添加到我的项目中,同时使用它。每个插件都描述了一个API和他的所有@Controller-s和Models。

我设法在我的Spring配置中注册了这些API-s(

AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
ctx.register(classNames);
ctx.refresh();

),但我怎么能"唤醒"我的春天,说请扫描所有这些控制器。

我为我的所有API-s都有一个ExceptionHandler,这就是为什么我需要扫描它们以将这些控制器与处理程序连接起来。

我试过这个,但没有用。

AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
ctx.scan(packageName);
ctx.refresh();

我在执行过程中没有出错。

将@RestController注释用于定义了所有API 的控制器类

@RestController
public class exampleController {
}

对其他组件类使用@Component注释

@Component
public class Validations {
}

此外,您还可以对定义了业务逻辑的业务层使用@Service注释,并对访问数据库的类使用@Repository批注。

要启用上面提到的注释,如果您使用"maven"来构建项目,则需要添加下面提到的依赖性。否则,将所有jar文件添加到与以下依赖性相关的项目中

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

如果您需要处理异常,您需要使用@ControllerAdvice注释创建下面提到的类。您可以为每个异常处理特定的方法。(示例:NullPointerException(

@ControllerAdvice
public class ExceptionHandler extends RuntimeException {
@Autowired
ResponceBuilder responseBuilder;
@JsonIgnore
private HttpStatus status = HttpStatus.OK;
public ExceptionHandler() {
super();
}
@org.springframework.web.bind.annotation.ExceptionHandler(Example.class)
public ResponseEntity<Response> 
NullPointerException(NullPointerException e) {
log.info("Invalid Data: {}",e.getErrorMessage());
return new ResponseEntity<>(responseBuilder.build(e.getErrorCode(), 
e.getErrorMessage()), status);
}

最新更新