当基于XML的spring mvc已加载时,扫描新的手动添加的控制器

我正在一个项目中,我们正在使用Spring MVC作为Web框架。 它具有基于xml的配置,并且首先启动。 但是我还有一些插件,可以在使用插件时手动将其添加到我的项目中。每个插件都使用其所有@ Controller-s和Models描述一个API。

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

AnnotationconfigWebApplicationContext ctx=new AnnotationconfigWebApplicationContext();
        ctx.register(classnames);
        ctx.refresh();

),  但是我怎样才能“唤醒”我的春天,并说请扫描所有这些控制器。

我所有API都有一个ExceptionHandler,这就是为什么我需要全部扫描它们以将这些Controller与处理程序连接的原因。

我已经尝试过了,但是没有用。

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

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

kathy86 回答:当基于XML的spring mvc已加载时,扫描新的手动添加的控制器

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

@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);
}
本文链接:https://www.f2er.com/3143928.html

大家都在问