gpt4 book ai didi

java - Spring @Autowired 字段为空。我在不同的类中使用@AutoWired Fields

转载 作者:行者123 更新时间:2023-12-01 10:40:26 36 4
gpt4 key购买 nike

这是我的类代码,其中有 @Autowired 字段:

测试A

@ContextConfiguration("classpath:spring.xml")
public abstract class TestA extends AbstractTestNGSpringContextTests {

@Autowired
@Value("#{environment.username}")
public String username;

@Autowired
@Value("#{environment.password}")
public String password;

@Autowired
@Value("#{environment.passwordtoken}")
public String passwordToken;
}

这是我尝试使用上述字符串变量的另一个类

public class TestData extends TestA {

ForceApi api;


public void setApi() {
// Instantiating api by setting username and pwd
System.out.println("In getApi");
ApiConfig ac = new ApiConfig();
ac.setUsername(username);
ac.setPassword(passwordToken); ac.setLoginEndpoint("https://login.salesforce.com/services/Soap/u/34.0/");

api = new ForceApi(ac);
}

public void pTestData() {

setApi();
// Create test data for play group admin
String idSoql = "SELECT id FROM PlayGroup__c";

List<Map> mapResults = api.query(idSoql).getRecords();
}
}

并尝试使用以下类执行测试:

public class TestB extends TestA{
@Test(dataProvider="browsers")
public void test1(){
TestData td = new TestData();
td.pTestData();
}

}

请帮我找出哪里做错了。我在这一行中遇到空指针异常:

List<Map> mapResults = api.query(idSoql).getRecords();

最佳答案

我自己解决了上述问题。

我在使用 @Autowired 字段的类中使用了 @Service("testdata")

@Service("testdata")
public class TestData extends TestA {

ForceApi api;


public void setApi() {
// Instantiating api by setting username and pwd
System.out.println("In getApi");
ApiConfig ac = new ApiConfig();
ac.setUsername(username);
ac.setPassword(passwordToken); ac.setLoginEndpoint("https://login.salesforce.com/services/Soap/u/34.0/");

api = new ForceApi(ac);
}

public void pTestData() {

setApi();
// Create test data for play group admin
String idSoql = "SELECT id FROM PlayGroup__c";

List<Map> mapResults = api.query(idSoql).getRecords();
}

}

在 TestB 中更改如下

public class TestB extends TestA{
@Test(dataProvider="browsers")
public void test1(){
TestData td = (TestData )applicationContext.getBean("testdata");
td.pTestData();
}

}

并在 spring.xml 中添加如下 bean

<bean id="testdata" class="data.TestData"/> 

这解决了我的空指针异常问题。

关于java - Spring @Autowired 字段为空。我在不同的类中使用@AutoWired Fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34449731/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com