Reputation: 237
We are upgrading the spring boot version from 1.3.0.RELEASE to 2.3.12.RELEASE. As per the old version, yml files were read using the following code snippet
@Configuration
@ConfigurationProperties(locations = "classpath:/config/myconf-source.yml")
public class MyConfigProperties {
private String configSource;
public String getConfigSource() {
return configSource;
}
public void setConfigSource(String configSource) {
this.configSource = configSource;
}
}
Config files in src/main/resources/config/
myconf-source.yml
news-source.yml
conf-mapping.yml
Content in myconf-source.yml
configSource: "TEST"
Corresponding Test Class
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@EnableAutoConfiguration
@SpringApplicationConfiguration(classes = SampleApplication.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@ConfigurationProperties(locations = "classpath:**/config/**")
public class MyConfigPropertiesTest {
@Autowired
private MyConfigProperties myConfigProperties;
@Test
public void testMyConfigProperties() {
String config = myConfigProperties.getConfigSource();
Assert.assertEquals(config, "TEST");
}
}
After changing to the new version, it throws an error Cannot resolve method 'locations'
.
If I remove locations
attribute how spring will know the class MyConfigProperties has to read myconf-source.yml
Also while running the test class, NullPointerException is thrown as myConfigProperties.getConfigSource();
becomes null.
I have tried various solutions posted but no luck,
Can anyone suggest how to make it work?
Thanks
Upvotes: 1
Views: 6629
Reputation: 18909
@Configuration
should be used if in that class you define beans with @Bean
.
If not then remove it from there.
Also @Configuration
does not make this class a bean to be autowired in the test that you require it to be.
If you want MyConfigProperties
to be available for autowiring then you also need
@EnableConfigurationProperties(MyConfigProperties.class)
. This will make sure that this class is available as a spring bean in the application context.
So it would be
@PropertySource("classpath:/config/myconf-source.yml")
@ConfigurationProperties()
@EnableConfigurationProperties(MyConfigProperties.class)
public class MyConfigProperties {
private String configSource;
public String getConfigSource() {
return configSource;
}
public void setConfigSource(String configSource) {
this.configSource = configSource;
}
}
Upvotes: 2
Reputation: 777
You can use @PropertySource annotation to read the yml file , you can read the below article :
https://www.baeldung.com/properties-with-spring
Upvotes: 0