Java Guice可以初始化bean吗?
我以前用过Spring(很喜欢),但我想看看它 有没有一种方法可以使用Guice将映射或列表之类的东西初始化到bean中 例如,我以前在Spring中做过以下工作,将要处理的项目列表注入到某个bean中Java Guice可以初始化bean吗?,java,dependency-injection,inversion-of-control,guice,Java,Dependency Injection,Inversion Of Control,Guice,我以前用过Spring(很喜欢),但我想看看它 有没有一种方法可以使用Guice将映射或列表之类的东西初始化到bean中 例如,我以前在Spring中做过以下工作,将要处理的项目列表注入到某个bean中 <property name="FilesToProcess"> <list> <value>file1.xml</value> <value>file2.xml</value> <
<property name="FilesToProcess">
<list>
<value>file1.xml</value>
<value>file2.xml</value>
</list>
</property>
file1.xml
file2.xml
如何在Guice中实现这一点?Guice2具有多绑定和映射绑定,应该适合您 更新: 再看一遍,您可能会问如何将运行时值注入Guice,可能是作为任意对象 Guice非常专注于做所有类型安全的代码,所以它不适合自己 当然是这样。我为Guice提供输入所做的是创建一个XML模式,并使用jaxb将其吸收并注入结果对象 有一个Names.bindProperties方法用于将常规旧属性绑定到GUI中 常数 与Spring还有一定程度的集成,因此您可能希望将其视为
嗯。Guice允许您注入类型文本。语法有点奇怪。有一种解释原因的方法 绑定看起来像这样:
public class SampleModule extends AbstractModule {
protected void configure() {
bind(new TypeLiteral<List<String>>() {}).
annotatedWith(Names.named("FilesToProcess")).
toInstance(Arrays.asList("file1.xml", "file2.xml"));
}
}
public class SampleClass {
private final List<String> files;
@Inject
public SampleClass(@Named("FilesToProcess") List<String> files) {
this.files = files;
}
}
公共类SampleModule扩展了AbstractModule{
受保护的void configure(){
绑定(新的TypeLiteral(){})。
注释为(Names.named(“FilesToProcess”))。
toInstance(Arrays.asList(“file1.xml”、“file2.xml”);
}
}
然后您的应用程序代码可以按名称插入列表,如下所示:
public class SampleModule extends AbstractModule {
protected void configure() {
bind(new TypeLiteral<List<String>>() {}).
annotatedWith(Names.named("FilesToProcess")).
toInstance(Arrays.asList("file1.xml", "file2.xml"));
}
}
public class SampleClass {
private final List<String> files;
@Inject
public SampleClass(@Named("FilesToProcess") List<String> files) {
this.files = files;
}
}
公共类SampleClass{
私人最终清单文件;
@注入
公共SampleClass(@Named(“FilesToProcess”)列表文件){
this.files=文件;
}
}
我同意Dave Stenglein关于运行时值的观点
有这样的框架专门用于配置。我喜欢Guice进行代码注入,但它们更适合配置注入。该链接已失效,是否有人可以提供指向该链接包含的相关信息的新链接?