Spring Boot 从服务调用 Rest Controller 方法

Ben*_*oki 2 java spring spring-rabbit spring-boot

我正在使用 Spring Boot 从服务调用休息控制器方法。当该方法被调用时,我收到错误 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的服务代码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Eir*_*dou 6

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

您的控制器是您的应用程序的集成点。您希望每个 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
   }

}
Run Code Online (Sandbox Code Playgroud)

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

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

   @Autowired
   private AuthService authService;

   public AuthModel addAuthenticatable(AuthModel auth){
       //process input etc..
       return authService.save(auth);
   }
}
Run Code Online (Sandbox Code Playgroud)

或在一个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);


}
Run Code Online (Sandbox Code Playgroud)

以及您的配置,以便您可以让 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();
   }
}
Run Code Online (Sandbox Code Playgroud)

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