0

Using Spring 5 on Java 9....

Not even sure this is possible. Have a very simple class:

public class Exchange {
  @Autowired
  private OtherService other;

  @JmsListener(destination = {some.queue})
  @Transactional
  public void receive(String payload) {
    other.send(payload)
  }
}

Both Exchange and OtherService just needs a couple of configuration properties (i.e. some.queue) to work. Would like to register (either through BeanDefinitionRegistryPostProcessor or ApplicationContextInitializer) multiple instances of the Exchange bean but with prefixed configuration properties. Anyway to alter attribute definition when registering a bean?

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Matthew Campbell
  • 1,864
  • 3
  • 24
  • 51

1 Answers1

1

I think you want a combination of two things, @ConfigurationProperties and @Qualifier.

ConfigurationProperties let's you supply a prefix that applies to all of the @Value properties loaded injected in tho that class.

@Qualifier allows you to specify which one of potentially many valid @Autowire targets you'd like. Specify the bean name and you are set.

Quick untested example:

@Component("FooExchange")
@ConfigurationProperties(prefix = "foo")
class FooExchange implements Exchange {
    @Value("enabled") private boolean enabled;
    ...
}

@Component("BarExchange")
@ConfigurationProperties(prefix = "bar")
class BarExchange implements Exchange {
    @Value("enabled") private boolean enabled;
    ...
}

And the properties you'd define are:

foo.enabled = true
bar.enabled = true

And when you inject one:

@Autowired
@Qualifier("FooExchange")
private Exchange myInjectedExchange; // Which will get FooExchange

Edit: You may beed to annotate one of your configuration classes or your main class with @EnableConfigurationProperties to enable the configuration properties.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Todd
  • 30,472
  • 11
  • 81
  • 89
  • Wasn't aware that ConfigurationProperties pushed over a prefix to Value attributes. Cool. Still wonder if it would be possible to register a bean but alter say the prefixes when registering? Don't need to inject (i.e. with Qualifier) the Exchange just have instances with different configuration. – Matthew Campbell Jan 10 '18 at 13:43