本文介紹了Guice屬性注入的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我的項(xiàng)目結(jié)構(gòu)如下:
其中我的Test1.java是這樣的:
package TestNG;
import org.testng.annotations.Test;
import com.google.inject.Inject;
import com.google.inject.name.Named;
public class Test1 {
@Inject
@Named("semi-auto.firstname")
String firstname;
@Test
public void test() {
System.out.println(firstname);
}
}
我的半自動(dòng)屬性是
semi-auto.firstname=John
semi-auto.lastname=Doe
我想做的是在使用Guice的Test1中使用‘Firstname’參數(shù)值。
測(cè)試通過(guò),但傳遞的值為空。
我不能這樣做嗎?
請(qǐng)幫幫忙
推薦答案
您需要編寫一個(gè)模塊來(lái)配置Guice以加載屬性文件(并綁定您擁有的任何其他依賴項(xiàng))。
class SemiAutoModule extends AbstractModule {
@Override
protected void configure() {
Properties defaults = new Properties();
defaults.setProperty("semi-auto.firstname", "default firstname");
try {
Properties properties = new Properties(defaults);
properties.load(ClassLoader.class.getResourceAsStream("semi-auto.properties"));
Names.bindProperties(binder(), props);
} catch (IOException e) {
logger.error("Could not load config: ", e);
System.exit(1);
}
}
};
然后您需要告訴TestNG:
@Guice(modules=SemiAutoModule.class)
public class Test1 {
@Inject
@Named("semi-auto.firstname")
String firstname;
@Test
public void test() {
System.out.println(firstname);
}
}
測(cè)試NG的文檔如下:http://testng.org/doc/documentation-main.html#guice-dependency-injection。
這篇關(guān)于Guice屬性注入的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,