从普通应用程序启动Springboot

时间:2019-11-11 16:15:59

标签: java spring-boot dependency-injection

我正在移植一台小型服务器以使用Springboot。传统上,服务器是通过简单的main方法启动的,该方法实例化一些逻辑对象,然后将它们传递给另一个启动Sparkjava服务的Server类。

代码看起来像这样:

class Main {
  public static void main(String[] args) {
    // parse args...
    MyLogicHandler handler = new MyLogicHandler(foo, bar, baz);
    Server server = new SparkServer(port, handler);
    server.start();
  }
}

class SparkServer {
  final int port;
  final MyLogicHandler handler;

  SparkServer(int port, MyLogicHandler handler) {
    this.port = port;
    this.handler = handler;
  }

  void start() {
    spark.Service service = spark.Service.ignite();
    service.get("/foo", (req, res) -> handler.foo());
    // ...
  }
}

我开始研究新的Spring服务器实现:

@SpringBootApplication
class SpringServer implements Server {
  final MyLogicHandler handler;

  @Bean
  MyLogicHandler getHandler() { return this.handler; }

  void setHandler(MyLogicHandler handler) { this.handler = handler; }

  void start() {
    SpringApplication.run(SpringServer.class)
  }
}

@RestController
class SpringRestController {
  final MyLogicHandler handler;

  // uses injection
  SpringRestController(MyLogicHandler handler) { this.handler = handler; }

  @GetMapping("/foo")
  String foo() {
    return handler.foo();
  }
}

(为了简洁起见,都省略了访问修饰符)

MyLogicHandler只是不应该知道任何框架或库的某些类-因此@Controller和朋友不起作用。

此代码失败,并显示以下消息:

Parameter 0 of constructor in SpringRestController required a bean of type 'MyLogicHandler' that could not be found.

The following candidates were found but could not be injected:
    - User-defined bean method 'getHandler' in 'SpringServer' ignored as the bean value is null

0 个答案:

没有答案