How to use autwire bean properties from condition

Is there a way to autwire bean able?

The following example. We have 2 implementation of FileManager. One implementation option should be initialized depending on the property platform. Properties are processed through Archaius.

@Component public class AwsPlatformCondition implements Condition { @Autowired private ArchaiusProperties archaiusProperties; @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return "aws".equalsIgnoreCase(archaiusProperties.getStringProperty(PropertiesMapper.PLATFORM)); } } 

.

 @Component public class StandardPlatformCondition implements Condition { @Autowired private ArchaiusProperties archaiusProperties; @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return "standard".equalsIgnoreCase(archaiusProperties.getStringProperty(PropertiesMapper.PLATFORM)); } } 

.

 @Component @Conditional(AwsPlatformCondition.class) public class AS3FileManager implements FileManager { ... } 

.

 @Component @Conditional(StandardPlatformCondition.class) public class NativeFileManager implements FileManager { ... } 

This code does not work. The main reason is that the ArchaiusProperties bean is not initialized when the condition is met. Is there a way to initialize an ArchaiusProperties bean before using it in state?

+5
source share
1 answer

If we look at java docs for the Condition interface -

Conditions must comply with the same restrictions as BeanFactoryPostProcessor , and try to never interact with bean instances.

Limitations: ( java docs BeanFactoryPostProcessor )

A BeanFactoryPostProcessor can interact with and modify bean definitions, but never bean instances. This can lead to premature bean creation, container malfunction, and unintended side effects.

So what you are trying to achieve is not recommended; which side effects have already occurred.

However, if we dig further in the documents for Condition , we get

For finer-grained control of the conditions that interact with @Configuration beans, consider the ConfigurationCondition interface.

It also violates restrictions. Therefore, everything in use with Condition in this scenario is not a good idea.

So IMO is best for you - go with @Profile , where you can activate your desired profile at a time and use the appropriate bean; excluding excesses.

+4
source

Source: https://habr.com/ru/post/1213513/


All Articles