...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
Creating Spring context
Code Block | ||
---|---|---|
| ||
public class InitAPIImpl implements InitAPI {
@Override
public void init(Vertx vertx, Context context, Handler<AsyncResult<Boolean>> handler) {
vertx.executeBlocking(
future -> {
SpringContextUtil.init(vertx, context, ApplicationConfig.class);
future.complete();
},
result -> {
if (result.succeeded()) {
handler.handle(Future.succeededFuture(true));
} else {
handler.handle(Future.failedFuture(result.cause()));
}
});
}
} |
We implemented class SpringContextUtil to use Spring dependency injection in Vert.x applications.
SpringContextUtil#init method initializes Spring context and adds it to Vertx Context object.
Accessing Spring context from endpoint classes
Code Block | ||
---|---|---|
| ||
public class EholdingsProxyTypesImpl implements EholdingsProxyTypes { private final Logger logger = LoggerFactory.getLogger(EholdingsProxyTypesImpl.class); @Autowired private RMAPIConfigurationService configurationService; @Autowired private ProxyConverter converter; @Autowired private HeaderValidator headerValidator; @SuppressWarnings("squid:S1172") public EholdingsProxyTypesImpl(Vertx vertx, String tenantId) { SpringContextUtil.autowireDependencies(this, vertxVertx.getOrCreateContextcurrentContext()); } |
SpringContextUtil#autowireDependencies method gets Spring context from Vertx context and uses it to inject beans into EholdingsProxyTypesImpl.
RestVerticle will call constructor with parameters (Vertx vertx, String tenantId) through reflection.@SuppressWarnings("squid:S1172") annotation is needed because Sonar can't see reflection calls and considers tenantId parameter to be unnecessarydefault constructor through reflection.
Declaring Spring configuration
SpringContextUtil#init uses Spring configuration class.
...
vertx and expirationTime parameters will be automatically injected by Spring, expirationTime will be set to the value of "configuration.cache.expire" property from application.properties file.
Benefits of using Spring DI
1) Spring allows to inject properties by using @Value annotation, without this we need to manually read file and share it across application.
...
Expand |
---|
private RMAPIConfigurationService configurationService; |
With Spring:
Expand |
---|
@Autowired } |
4) It resolves circular dependencies between objects.
...
6) Objects are created once instead of being created on each request.
Presentation on dependency injection Spring_DI.pptx