java Guice属性注入

laik7k3q  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(150)

我有我的项目结构如下:

我的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。我不能这样做吗?请帮助

iecba09b

iecba09b1#

您需要编写一个模块来配置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(), properties);
            } 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);
    }

}

The documentation for TestNG is here: http://testng.org/doc/documentation-main.html#guice-dependency-injection.

相关问题