我正在使用1.5.8.RELEASE开发一个Spring Boot应用程序,它是通过CLI配置和运行的。这些参数用于将应用程序配置为以一种或多种不同方式运行。其中一个命令是运行所有黄瓜功能,并使用以下命令调用:
cucumber.api.cli.Main.main(cucumberArguments);
当前传递的参数包括:featureFolder
,-g
,stepsPackage
以及一些黄瓜报告配置参数。
我希望能够通过我的application.properties文件或通过特定于配置文件的application.properties文件在我的CucumberSteps * .java文件中配置一些属性,但我现在运行这些功能的方式意味着没有加载Spring Boot上下文。
我的第一次尝试是:
@ConfigurationProperties
public class CucumberStepsFeature1 {
@Value("${my.property}")
private String myProperty;
@Given("...")
public void given() {
// fails below
assertNotNull(this.myProperty);
}
}
我解决这个问题的第二次尝试是:
@ContextConfiguration(classes = MyMainApp.class)
@ConfigurationProperties
public class CucumberStepsFeature1 {
@Value("${my.property}")
private String myProperty;
@Given("...")
public void given() {
// fails below
assertNotNull(this.myProperty);
}
}
但是我收到了
的错误消息Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
我尝试跟随steps listed here,但无济于事。
我很感激任何帮助的尝试,但我现在注意到,由于公司政策,我在这里分享的内容将非常有限。我无法复制或粘贴任何真实的代码片段或日志。
答案 0 :(得分:0)
以下是我能找到的最干净的方式来实现我想要的目标:
创建一个Config类,以加载您需要的Spring应用程序属性(application.properties和/或application - $ {PROFILE} .properties),如下所示:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties
public class PropsConfig {
@Value("${my.property}")
private String myProperty;
//any other properties...
public String getMyProperty() {
return this.myProperty;
}
创建另一个类作为Spring ApplicationContext的容器。确保Spring将它放在主应用程序类的子包中进行扫描。请参阅以下代码:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringApplicationContextContainer implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Autowired
public SpringApplicationContextContainer(ApplicationContext applicationContext) {
SpringApplicationContextContainer.applicationContext = applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringApplicationContextContainer.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return SpringApplicationContextContainer.applicationContext;
}
}
最后,在您的CucumberSteps类或任何其他非Spring类中,您只需拨打SpringApplicationContextContainer.getApplicationContext();
,如下所示:
public class CucumberStepsFeature1 {
private final PropsConfig propsConfig;
public CucumberStepsFeature1() {
this.propsConfig = SpringApplicationContextContainer.getApplicationContext().getBean(PropsConfig.class);
}
@Given("...")
public void given() {
// passes below
assertNotNull(this.propsConfig);
}