我被困住了!如果我跳过测试并部署到tomcat自动布线,则配置属性文件可以正常工作。在我的测试中,它失败了!我不确定我错过了什么。
这是我的设置:
Spring Boot v 1.2.5.RELEASE Application.yml
git:
localRepo: './powershell-status-scripts/'
remoteRepo: 'https://github.com/...'
RepositoryProperties此类具有属性的getter和setter
@Configuration
@ConfigurationProperties(locations = "classpath:application.yml", prefix = "git", ignoreUnknownFields = false)
public class RepositoryProperties {
private String localRepo;
private String remoteRepo;
public RepositoryProperties() {
}
public String getLocalRepo() {
return localRepo;
}
public void setLocalRepo(String localRepo) {
this.localRepo = localRepo;
}
public String getRemoteRepo() {
return remoteRepo;
}
public void setRemoteRepo(String remoteRepo) {
this.remoteRepo = remoteRepo;
}
}
Application.java
@EnableAutoConfiguration
@EnableConfigurationProperties
@ComponentScan(basePackages = "com.sendash.admin")
@EnableJpaRepositories("com.sendash.admin.dao.jpa")
@EnableSwagger
public class Application extends SpringBootServletInitializer {
private static final Class<Application> applicationClass = Application.class;
private static final Logger log = LoggerFactory.getLogger(applicationClass);
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
}
GitService - 自动装配属性适用于tomcat!
@Service
@EnableConfigurationProperties
public class GitService {
@Autowired
private RepositoryProperties repositoryProperties;
public void updateLocalRepository() {
...
}
GitServiceTest由于NPE,此类在init上失败。属性为空。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
@Profile("test")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
public class GitServiceTest {
@Autowired
private static GitService manager;
@Autowired
private static RepositoryProperties properties;
private static final String localRepoLocation = properties.getLocalRepo();
我确实认识到@EnableConfigurationProperties在Application.java和GitService.java类之后。停止复制并不能解决问题。
答案 0 :(得分:1)
如果要在测试中使用Spring Boot,则应相应地配置测试。为此,请删除ContextConfiguration并添加以下内容:
@SpringApplicationConfiguration(classes = Application.class, initializers = ConfigFileApplicationContextInitializer.class)
这应该可以启用注入配置属性。