我想要得到一個Spring引導應用程序去,我不知道我在做什麼錯在這裏。我在src/main/resources & src/test/resources中有一個application.properties文件。我有我的ConfigurationSettings的@Bean,這樣我可以在我的應用程序中使用它們:彈簧引導屬性不@ @ Autowired
@Component
public class ConfigurationSettings {
private String product;
private String version;
private String copyright;
private String appName;
private String appDescription;
...
// getters and setters
}
這裏是我踢的應用程序關閉:
@Configuration
@EnableJpaRepositories
@EnableAutoConfiguration
@EnableConfigurationProperties
@PropertySources(value = {@PropertySource("classpath:application.properties")})
@ComponentScan(basePackages = "com.product")
@EnableScheduling
public class OFAC {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(OFAC.class, args);
}
這裏是我的配置類:
@Configuration
@ComponentScan(basePackages = {"com.product"})
@PropertySources(value = {@PropertySource("classpath:application.properties")})
public class OFAConfiguration {
@Autowired
private Environment env;
@Bean
public ConfigurationSettings configurationSettings() {
ConfigurationSettings configurationSettings = new ConfigurationSettings();
configurationSettings.setAppDescription(env.getRequiredProperty("app.description"));
configurationSettings.setAppName(env.getRequiredProperty("app.name"));
configurationSettings.setServerPort(env.getRequiredProperty("server.port"));
return configurationSettings;
}
我想在一個控制器來使用它:
@RestController
public class AboutController {
@Autowired
private ConfigurationSettings configurationSettings;
@RequestMapping(value = "/about", method = RequestMethod.GET)
public About index() {
String product = configurationSettings.getProduct();
String version = configurationSettings.getVersion();
String copyright = configurationSettings.getCopyright();
return new About(product, version, copyright);
}
}
但是,通過此步驟時,ConfigurationSettings的所有值都爲空。我有一個測試,成功加載的值:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {OFAConfiguration.class})
public class OFAConfigurationTest {
@Autowired
private Environment environment;
@Autowired
private ConfigurationSettings configurationSettings;
@Test
public void testConfigurationLoads() {
assertNotNull(environment);
Assert.assertNotNull(configurationSettings);
}
@Test
public void testConfigurationSettingValues() {
assertEquals("Product Name", configurationSettings.getProduct());
assertEquals("0.0.1", configurationSettings.getVersion());
assertEquals("2014 Product", configurationSettings.getCopyright());
}
任何人都可以看到爲什麼ConfigurationSettings沒有填充在我的控制器?
軟件包「com.product」中是否有'OFAConfiguration'?如果沒有,那麼它不會被加載到上下文中。 –
N.B.你的'@ PropertySources'在Spring Boot應用程序中是多餘的(儘管如此,一定要在你的測試中使用'@ SpringApplicationConfiguration')。如果你使用'@ EnableAutoCOnfiguration',你也有'@ EnableConfigurationProperties'這是多餘的。在你的'ConfigurationSettings'上實際使用'@ ConfigurationProperties'可能會更好一些(然後你不必手動將它綁定到環境 - 由你決定)。 –
你有兩個'ConfigurationSettings'實例。一個由'@ Bean'註釋的方法創建,另一個由於組件掃描(它有一個'@ Component'註釋')。一個壓倒另一個。刪除'@ Component'註釋。 –