J'ai essayé d'obtenir un exemple très basique d'une PropertySource personnalisée exécutée dans une application Spring.Spring PropertySourcesPlaceholderConfigurer n'utilise pas PropertySource personnalisé pour @Value
Ceci est mon PropertySource:
public class RemotePropertySource extends PropertySource{
public RemotePropertySource(String name, Object source) {
super(name, source);
}
public RemotePropertySource(String name) {
super(name);
}
public Object getProperty(String s) {
return "foo"+s;
}
}
Il est ajouté à la ApplicationContext via un ApplicationContextInitializer:
public class RemotePropertyApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
public void initialize(GenericApplicationContext ctx) {
RemotePropertySource remotePropertySource = new RemotePropertySource("remote");
ctx.getEnvironment().getPropertySources().addFirst(remotePropertySource);
System.out.println("Initializer registered PropertySource");
}
}
Maintenant, je créé une unité simple test pour voir si le PropertySource est utilisé correctement:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RemotePropertySourceTest.ContextConfig.class, initializers = RemotePropertyApplicationContextInitializer.class)
public class RemotePropertySourceTest {
@Autowired
private UnderTest underTest;
@Autowired
Environment env;
@Test
public void testContext() {
assertEquals(env.getProperty("bar"),"foobar");
assertEquals(underTest.getFoo(),"footest");
}
@Component
protected static class UnderTest {
private String foo;
@Autowired
public void setFoo(@Value("test")String value){
foo=value;
}
public String getFoo(){
return foo;
}
}
@Configuration
@ComponentScan(basePackages = {"test.property"})
protected static class ContextConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
return configurer;
}
}
}
Accéder à la valeur via l'environnement me donne t Le résultat correct ("foobar"), mais l'utilisation de @ Value-Annotation échoue. Pour autant que j'ai lu dans la documentation, le PropertySourcesPlaceholderConfigurer de ma Configuration devrait automatiquement récupérer ma PropertySource de l'environnement, mais apparemment ce n'est pas le cas. Y a-t-il quelque chose qui me manque?
Je sais que l'accès aux propriétés explicitement via l'environnement est préférable, mais l'application existante utilise beaucoup @ Value-Annotations.
Toute aide est grandement appréciée. Merci!
Eh bien, maintenant je me sens vraiment stupide. J'étais tellement concentré sur l'obtention du contexte que j'ai utilisé la mauvaise syntaxe. Merci! –