The*_*boy 7 java dependency-injection spark-java
在.NET工作之后,我非常精通NancyFX和Web API等微型Web框架对IoC容器的支持.
在像Sinatra这样的Ruby类似框架中(NancyFX基于Sinatra),似乎你有依赖注入的能力.
从我看到的,因为Java spark应用程序作为主要方法运行,似乎你不能传入依赖项或IoC容器.
public class HelloWorld {
public static void main(String[] args) {
get("/hello", (req, res) -> "Hello World");
}
}
Run Code Online (Sandbox Code Playgroud)
我很难理解这样的框架在没有支持的情况下如何有用.
如果这个框架没有,那么是否有另一个轻量级框架(Spring不是我记忆中的轻量级框架,但可能已经发生了变化),它确实支持这个吗?
小智 8
Spring可以简单地与Spark集成.例如
public interface Spark {
/**
* adds filters, routes, exceptions, websockets and others
*/
void register();
}
@Configuration
public class SparkConfiguration {
@Autowired(required = false)
private List<Spark> sparks = new ArrayList<>();
@Bean
CommandLineRunner sparkRunner() {
return args -> sparks.stream().forEach( spark -> spark.register());
}
}
@Component
public class HelloSpark implements Spark {
@Autowired
private HelloWorldService helloWorldService;
@Override
public void register() {
get("/hello", (request, response) -> helloWorldService.hello() );
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在https://github.com/pmackowski/spring-boot-spark-java上找到更多信息
在 Java Spark 中使用 Guice 非常容易。基本上,您需要SparkFilter按以下方式扩展以创建 Guice 注入器。
public class SparkGuiceFilter extends SparkFilter {
private Injector injector = null;
@Override
protected SparkApplication[] getApplications(final FilterConfig filterConfig) throws ServletException {
final SparkApplication[] applications = super.getApplications(filterConfig);
if (this.injector == null) {
this.injector = Guice.createInjector(new MainModule());
}
if (applications != null && applications.length != 0) {
for (SparkApplication application : applications) {
this.injector.injectMembers(application);
}
}
return applications;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要一个web.xml并且必须war使用 Jetty 或任何其他 servlet 容器将 Spark 应用程序作为普通应用程序运行:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<filter>
<filter-name>SparkGuiceFilter</filter-name>
<filter-class>com.devng.spark.guice.SparkGuiceFilter</filter-class>
<init-param>
<param-name>applicationClass</param-name>
<param-value>com.devng.spark.SparkApp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SparkGuiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Run Code Online (Sandbox Code Playgroud)
但是,这种方法有一些限制。您不能在 Guice 中使用基于请求或会话的范围。如果您不需要这个,那么您就可以开始了,否则您需要集成 Guice Servlet Extensions 并按照官方 Guice 文档中的描述将其添加到GuiceFilter您的web.xml中。您还需要确保您使用相同的喷射器的实例在和这样做,你需要定义一个你所描述这里。GuiceFilterSparkGuiceFilterGuiceServletContextListenerweb.xml
你可以在我的 GitHub 中找到一个完整的示例https://github.com/devng/demo/tree/master/sparkjava-guice
| 归档时间: |
|
| 查看次数: |
6598 次 |
| 最近记录: |