Skip to content

Instantly share code, notes, and snippets.

@tonvanbart
Last active March 6, 2018 22:32
Show Gist options
  • Save tonvanbart/d64142735746f10326585043e0e2681e to your computer and use it in GitHub Desktop.
Save tonvanbart/d64142735746f10326585043e0e2681e to your computer and use it in GitHub Desktop.
Quick try-out of property resolution in Spring tests. As it turned out there was an application.properties in src/test/resources which was masking the one in src/main. @Autowiring the ApplicationContext enables browsing the contents in a debugger to see what's going on.
package testing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Probeersel.class)
@PropertySource("classpath:application.properties")
public class Probeersel {
@Value("${offer.fiber.postcodes.csv}")
String filename;
@Bean
public GetSet one() {
return new GetSet("one", null);
}
@Bean
public GetSet two(GetSet one, @Value("${offer.fiber.postcodes.csv:fallback}") String value) {
GetSet second = new GetSet("TWO", one);
// second.setValue(value);
return second;
}
@Autowired
GetSet two;
@Autowired
ApplicationContext applicationContext;
@Test
public void testOne() {
assertNotNull(filename);
System.out.println(filename);
System.out.println(two);
}
class GetSet {
private String name;
private GetSet inner;
@Value("${offer.fiber.postcodes.csv:default value}")
String value;
public GetSet(String name, GetSet inner) {
this.name = name;
this.inner = inner;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "GetSet{" +
"name='" + name + '\'' +
", inner=" + inner +
", value=" + value +
'}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment