Ich habe eine Spring-Boot-App. Ich möchte die Variable aus application.properties in der Klassenmethode verwenden, aber ich habe nullPointerException.NullPointerException bei der Verwendung von Bean in der Klassenmethode
Hier ist ein einfaches Beispiel, das nicht funktioniert.
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()));
}
}
Warum gibt config.getScreenshotsPath()
Methode Pfad nicht zurück. config
ist null.
Können Sie Ihre Klasse mit @SpringBootApplication kommentieren? –
Autowiring funktioniert nicht in einem 'TestExecutionListener'. –
Mögliches Duplikat von [Spring @ Value-Annotation wird immer als null bewertet?] (Https://stackoverflow.com/questions/4130486/spring-value-annotation-always-evaluating-as-null) –