我有一个Spring-boot应用程序。 我想在类方法中使用application.properties中的变量,但我有nullPointerException。
这是一个不起作用的简单例子。
application.properties:
#data paths
file.path=C:\\Users\\apodar\\autoTest
Config.java
package com.eserv.autotest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Config {
@Value("${file.path}")
String filePath;
public String getFilePath() { return filePath; }
public String getScreenshotsPath() {
return getFilePath() + "/screenshots";
}
}
AutotestApplication.java
package com.eserv.autotest;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.Transactional;
@SpringBootApplication(
scanBasePackageClasses = {
AutotestApplication.class,
}
)
public class AutotestApplication implements CommandLineRunner {
@Autowired DataSource dataSource;
public static void main(String[] args) {
SpringApplication.run(AutotestApplication.class, args);
}
@Transactional(readOnly = true)
@Override
public void run(String... args) throws Exception {
System.out.println("DATASOURCE = " + dataSource);
}
}
SeleniumTestExecutionListener:
public class SeleniumTestExecutionListener extends AbstractTestExecutionListener {
@Inject Config config;
private WebDriver webDriver;
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
if (testContext.getTestException() == null) {
return;
}
File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
String testName = toLowerUnderscore(testContext.getTestClass().getSimpleName());
String methodName = toLowerUnderscore(testContext.getTestMethod().getName());
FileUtils.copyFile(screenshot, new File( config.getScreenshotsPath() + testName + "_" + methodName + "_" + screenshot.getName()));
}
}
为什么config.getScreenshotsPath()
方法不返回路径。 config
为空。
答案 0 :(得分:0)
TestExecutionListener
中的自动装配将无效。 TestExecutionListener
实例的创建和生命周期由Spring的Test Context框架管理,它不是ApplicationContext
的一部分,而是外部的。因此,自动接线不起作用。
如果您想在TestExecutionListener
中使用bean,而是从ApplicationContext
检索TestContext
。
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
if (testContext.getTestException() == null) {
return;
}
final Config config = testContext.getApplicationContext().getBean(Config.class);
File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
String testName = toLowerUnderscore(testContext.getTestClass().getSimpleName());
String methodName = toLowerUnderscore(testContext.getTestMethod().getName());
FileUtils.copyFile(screenshot, new File( config.getScreenshotsPath() + testName + "_" + methodName + "_" + screenshot.getName()));
}