Spring Boot从服务中调用Rest Controller方法

本杰明·温德瓦·蒙约基

我正在使用Spring Boot从服务中调用rest控制器方法。调用该方法时,出现错误java.lang.NullPointerException广义的情况是,我的服务从RabbitMQ队列接收一个有效负载,并提取该有效负载的内容,然后将其传递给控制器​​以保存到数据库中。队列部分起作用(我可以从队列中接收消息并提取内容)。数据库部分也起作用。问题是从服务中调用控制器方法。

这是我的休息控制器

@RestController
@RequestMapping("/auth")
public class AuthController implements AuthService {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    AuthRepository authRepository;


    public AuthModel addAuthenticatable(AuthModel auth){
        auth.setCreatedAt(DateTimeUtility.getDateTime());
        return authRepository.save(auth);
    }
}

我的服务代码:

public class QueueListener extends AuthController implements MessageListener{
    private String identifier;
    private JSONArray globalObject;
    private int userId;
    private String pin;

    @Autowired
    AuthController authController;

    @Override
    public void onMessage(Message message) {
        String msg = new String(message.getBody());
        String output = msg.replaceAll("\\\\", "");
        String jsonified = output.substring(1, output.length()-1);

        JSONArray obj = new JSONArray(jsonified);
        this.globalObject = obj;
        this.identifier = obj.getJSONObject(0).getString("identifier");
        resolveMessage();
    }
    public void resolveMessage() {
        if(identifier.equalsIgnoreCase("ADD_TO_AUTH")) {
            for(int i = 0; i < globalObject.length(); i++){ 
                JSONObject o = globalObject.getJSONObject(i);
                this.userId = Integer.parseInt(o.getString("userId"));
                this.pin = o.getString("pin");
            }

            AuthModel authModel = new AuthModel();
            authModel.setUserId(userId);
            authModel.setPin(pin);

            authController.addAuthenticatable(authModel);
        }
    }
}

当我调用AuthController中的方法addAuthenticatable()时发生错误。任何帮助将不胜感激。

埃里尼·格罗尼杜(Eirini Graonidou)

我希望这不会超出主题,但是通常我们想要实现的是一种洋葱架构。依赖关系应该有一个方向。

控制器是应用程序的集成点。您希望每个REST触发某些逻辑的执行您的控制器不应扩展与业务逻辑有关的类或实现接口。此部分属于另一层。

关于逻辑的一切都属于服务:

@Service
public class AuthService {
    @Autowired
    private AuthRepository authRepository;

    private String attribute;

    public boolean isAuthenticated(String username) {
        authRepository.doSomething();
        //implementation of the logic to check if a user is authenticated.
    }

   public boolean authenticate(String username, char[] password) {
       // implementation of logic to authenticate.
       authRepository.authenticate();
   }

   public AuthModel save(AuthModel model) {
       //implementation of saving the model
   }

}

在服务层中提取逻辑,使事情可重用。现在,您可以将服务注入到controller

@RestController
@RequestMapping("/auth")
public class AuthController {

   @Autowired
   private AuthService authService;

   public AuthModel addAuthenticatable(AuthModel auth){
       //process input etc..
       return authService.save(auth);
   }
}

或在 amqListener

@Component
public class QueueListener implements MessageListener {
   @Autowired
   private AuthService authService;

   @Autowired
   private SomeOtherService otherService;

   @Override
   public void onMessage(Message message) {
      JSONArray array = processInput();

      JSONArray obj = new JSONArray(jsonified);
      String identifier = obj.getJSONObject(0).getString("identifier");
      // extract the business logic to the service layer. Don't mix layer responsibilities
      otherService.doYourThing(obj, identifier);

      resolveMessage();
  }

  private JSONArray processInput(Message message) {
     String msg = new String(message.getBody());
     String output = msg.replaceAll("\\\\", "");
     String jsonified = output.substring(1, output.length()-1);


}

和您的配置,以便您可以让spring知道在哪里寻找带注释的类。

@Configuration
@ComponentScan({"your.service.packages"})
@EntityScan(basePackages = "your.model.package")
@EnableJpaRepositories("your.repository.packages")
@EnableRabbit // probaby
@EnableWebMvc // probably
public class Config {
   //you could also define other beans here
   @Bean
   public SomeBean someBean() {
       return new SomeBean();
   }
}

@pvpkiran给出了您实际问题的答案。但我希望这对您有帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Spring Boot中未调用Rest Controller方法

Spring Controller方法被多次调用

我们可以在 apache kafka 消费者中从 spring boot rest api 应用程序调用服务方法吗?

执行Pre Handle方法后未调用Spring Rest Controller

在Spring的@Controller类中从单个方法调用两个不同的服务是否很好?

如何在Spring Boot中在Rest Controller方法端点上应用JSONignore注释?

在Spring Boot中何处放置调用REST API和修改实体的方法

在Spring中如何从其他Controller调用RestController方法?

Spring Controller中的Init方法(注释版本)

在Spring Controller中获取参数的简便方法?

Spring:在同一个 Rest Controller 函数中调用 2 个服务函数时出现空指针异常

在Spring Boot成功部署后调用服务方法

无法在Spring RestController中调用REST服务

Spring Boot Rest服务| 请求方法“ GET”不受支持

在Spring-Boot中从服务器调用另一个Rest API

使用自己的方法结果再次调用Spring Controller方法

Rest Controller无法在Spring Boot App中识别GET请求

使用Kotlin解决Spring Boot Rest Controller中的单例

在Spring Boot Rest Controller中处理压缩的json请求

Spring Boot:调用受OAuth2保护的REST服务

Spring Rest Controller通过ID / ID方法查找

Spring boot无法显示jsp页面但运行Controller映射方法

Spring Boot Controller不支持请求方法'GET'

Spring Boot Rest Controller非常慢的响应

用于Spring Boot Rest Controller的Junit

Spring Boot拦截服务方法

在单元测试中模拟Spring Controller方法模型绑定

在Spring Controller中获取语言环境的绝佳方法

在 @Async 方法中通过 Spring RestTemplate 调用 Rest API