You're on the right track, but there are a few common pitfalls when using @PropertySource with Spring and JUnit tests. Here’s a checklist and some solutions to ensure your properties are loaded and injected correctly:
1. Enable Property Placeholder Resolution
Spring does not automatically resolve ${...} placeholders from @PropertySource unless you explicitly register a PropertySourcesPlaceholderConfigurer bean.
In your BeanConfig class, add:
@Configuration
@PropertySource("classpath:ospeadapter.properties")
public class BeanConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
// other beans...
}
2. Inject Properties
You can now inject properties using @Value:
@Value("${your.property.name}")
private String yourProperty;
3. Test Class Setup
Your test class should look like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = BeanConfig.class)
public class DynsTest {
@Value("${your.property.name}")
private String yourProperty;
@Test
public void testProperty() {
System.out.println(yourProperty);
// assertions...
}
}
Note:
You do not need @PropertySource on the test class if it’s already on your config class.
4. Check Property File Location
Make sure ospeadapter.properties is in src/test/resources or src/main/resources so it’s on the classpath.
5. No Need for @PropertySource on Test Class
Remove @PropertySource from the test class. It should only be on the configuration class.
6. Spring Boot Alternative
If you’re using Spring Boot, you can just use @SpringBootTest and put your properties in application.properties or application-test.properties.
Summary
- Add
PropertySourcesPlaceholderConfigurer bean to your config.
- Use
@Value to inject properties.
- Ensure the property file is on the classpath.
- Only annotate the config class with
@PropertySource.
If you still have issues, please share:
- How you’re trying to inject the properties.
- The error message or what’s not working.
- The structure of your project (where the properties file is located).
Let me know if you need a full example!