【问题标题】:Guice properties injectionGuice 属性注入
【发布时间】:2017-05-28 03:46:52
【问题描述】:

我的项目结构如下:

我的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);
}

}

而我的 semi-auto.properties 是

semi-auto.firstname=John
semi-auto.lastname=Doe

我想要做的是使用 Guice 在 Test1 中使用 'firstname' 参数值。 测试通过,但通过的值为 null。 我不能这样吗? 请帮忙

【问题讨论】:

    标签: java guice dependency-properties


    【解决方案1】:

    您需要编写一个模块来配置 guice 以加载属性文件(并绑定到您拥有的任何其他依赖项中)。

    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);
        }
    
    }
    

    TestNG 的文档在这里:http://testng.org/doc/documentation-main.html#guice-dependency-injection

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2016-09-22
      相关资源
      最近更新 更多