我开始使用Dropwizard,我正在尝试创建一个需要使用数据库的Command.如果有人想知道我为什么要这样做,我可以提供充分的理由,但无论如何这不是我的问题.它是关于Dropwizard中的依赖性反转和服务初始化以及运行阶段.
Dropwizard鼓励使用它的DbiFactory来构建DBI实例,但是为了得到一个,你需要一个Environment实例和/或数据库配置:
public class ConsoleService extends Service<ConsoleConfiguration> {
public static void main(String... args) throws Exception {
new ConsoleService().run(args);
}
@Override
public void initialize(Bootstrap<ConsoleConfiguration> bootstrap) {
bootstrap.setName("console");
bootstrap.addCommand(new InsertSomeDataCommand(/** Some deps should be here **/));
}
@Override
public void run(ConsoleConfiguration config, Environment environment) throws ClassNotFoundException {
final DBIFactory factory = new DBIFactory();
final DBI jdbi = factory.build(environment, config.getDatabaseConfiguration(), "postgresql");
// This is the dependency I'd want to inject up there
final SomeDAO dao …Run Code Online (Sandbox Code Playgroud) 据我所知,Java8中的Streams只能收集一次(如在forEach()终止中),但我想知道我们是否可以设法在一系列过滤和映射任务中间"挖掘"到流中以产生一些附带效果.
从本质上讲,"点击"就像在做一个forEach()但是在管道的那个点返回Stream.
我会像这样使用它:
List<User> createAndPersistRandomUsers(int count) {
return IntStream.range(0, count)
.boxed() // returns Stream<Integer>
.map(UserBuilder::random) // returns Stream<User>
.tap(userRepo::persist) // Collateral persist of user, returns Stream<User>
.collect(toList()); // returns List<User>
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
根据Java关于类型擦除和有界类型参数的文档,我理解在下面的代码示例中,两个版本doStuff()将具有相同的擦除,因此不会编译.我的目标是超载doStuff()以接收ClassOne和收集ClassTwo.
import java.util.List;
class Example {
class ClassOne {
}
class ClassTwo {
}
public void doStuff(List<ClassOne> collection) {
}
public void doStuff(List<ClassTwo> collection) {
}
}
Run Code Online (Sandbox Code Playgroud)
类型擦除的机制包括以下步骤:
· 如果类型参数是无界的,则用泛型或对象替换泛型类型中的所有类型参数.因此,生成的字节码仅包含普通的类,接口和方法.
因此,我应该能够应用一个绑定,然后它将编译,因为现在类型擦除版本的doStuff重载了两个不同的签名(声明的上限).例:
class Example {
class ClassOne {
}
class ClassTwo {
}
public <U extends ClassOne> void doStuff(List<U> collection) {
}
public <U extends ClassTwo> void doStuff(List<U> collection) {
}
}
Run Code Online (Sandbox Code Playgroud)
第二个例子实际上没有编译并给出以下错误:
错误:(15,36)java:name clash:doStuff(java.util.List)和doStuff(java.util.List)具有相同的擦除
任何人都可以向我解释这个吗?