我一直在使用spring作为我的IOC。它还有一种非常好的方法可以在bean中注入属性。
现在我正在参与IOC为Guice的新项目。我不完全理解这个概念应该如何使用Guice将属性注入到我的bean中。
问题:是否有可能将原始属性(字符串,整数)注入我的guice bean。如果答案是否定的,那么您可能知道一些不错的Java特性框架。 因为我现在想在我的应用程序中使用ResourceBundle类进行简单的属性管理。但是在使用弹簧一段时间之后,这似乎并不适合我。
答案 0 :(得分:2)
this SO post讨论了各种配置框架的使用,以及属性的使用。我不确定它是否完全满足您的需求,但也许您可以在那里找到有价值的东西。
答案 1 :(得分:2)
Spring提供了在XML文件中找到的配置信息的注入。我不希望安装我的软件的人必须编辑XML文件,因此对于纯文本文件中的配置信息(如路径信息),我已经回到使用java.util.Properties了。因为它很容易使用并且非常适合Spring,如果你使用ClassPathResource,它允许文件本身的无路径定位(它只需要在类路径中;我把它放在WEB-INF / classes的根目录下。
这是一个返回填充的Properties对象的快速方法:
/**
* Load the Properties based on the property file specified
* by <tt>filename</tt>, which must exist on the classpath
* (e.g., "myapp-config.properties").
*/
public Properties loadPropertiesFromClassPath( String filename )
throws IOException
{
Properties properties = new Properties();
if ( filename != null ) {
Resource rsrc = new ClassPathResource(filename);
log.info("loading properties from filename " + rsrc.getFilename() );
InputStream in = rsrc.getInputStream();
log.info( properties.size() + " properties prior to load" );
properties.load(in);
log.info( properties.size() + " properties after load" );
}
return properties;
}
文件本身使用普通的“name = value”纯文本格式,但是如果要使用Properties的XML格式,只需将properties.load(InputStream)更改为properties.loadFromXML(InputStream)。 希望有所帮助。
答案 2 :(得分:1)
在Guice中注入属性很容易。从文件中读取某些属性后,或者使用Names.bindProperties(Binder,Properties)绑定它们。然后,您可以使用@Named("some.port") int port
。