简体   繁体   English

无法使用Java注释跨各种类对TestNG使用spring依赖项注入(JSR 330标准注释)

[英]Not able to use spring dependency injection across various classes for TestNG using java annotations(JSR 330 Standard Annotations)

I have a service which I am trying to inject across various classes in my tests but I am getting its instance as null. 我有一项服务,试图在测试中跨各种类注入服务,但我将其实例作为null。

My config interface: 我的配置界面:

MyService.java

public interface MyService {

    public String getHostUri();

}

My implementation class of this interface: MyServiceImpl.java 该接口的实现类: MyServiceImpl.java

public class MyServiceImpl implements MyService {

    private static final String BASE_HOST_URI_CONFIG = "localhost:4444";

    @Override
    public String getHostUri() {
        return BASE_HOST_URI_CONFIG;
    }

My Spring configuration class with the bean: 我的Spring配置类与bean:

@Configuration

public class AutomationSpringConfig {

    @Bean
    public MyService getMyService(){
        return new MyServiceImpl();
    }

}

My testNG class: 我的testNG课:

@ContextConfiguration(classes=AutomationSpringConfig.class ,loader =AnnotationConfigContextLoader.class)

public class BasicAutomatedTest extends AbstractTestNGSpringContextTests {

    private static final Logger LOGGER = Logger.getLogger(BasicAutomatedTest.class);

    @Inject
    private MyService myService;


    @Test
    public void basicTest {
        Setup setup = new Setup();
        LOGGER.info(myService.getHostUri());
        LOGGER.info(setup.myService.getHostUri());

    }
}

My helper class in which I am not able to get the injection: 我无法获得注射的助手班:

public class Setup {

  @Inject

  public MyService myService;

}

So when I try to get the hostUri via the setup object in the BasicAutomatedTest's basicTest method I get a NullPointerException. 因此,当我尝试通过BasicAutomatedTest的basicTest方法中的设置对象获取hostUri时,我得到了NullPointerException。 So I am not able to inject the MyService bean in the Setup class. 因此,我无法将MyService bean注入Setup类。

In order to use annotations you need to specify that behaviour in your beans XML configuration file. 为了使用注释,您需要在bean XML配置文件中指定该行为。 Something like this: 像这样:

<context:component-scan base-package="your.base.package"/>
<context:annotation-config/>

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM