com.chibchasoft.vertx.spring.SpringVerticleFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vertx-spring-verticle-factory Show documentation
Show all versions of vertx-spring-verticle-factory Show documentation
Spring-based Verticle Factory for Vert.x
/*
* Copyright (c) 2016 chibchasoft.com
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Apache License v2.0 which accompanies
* this distribution.
*
* The Apache License v2.0 is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Author Juan Velez
*/
package com.chibchasoft.vertx.spring;
import org.springframework.context.ApplicationContext;
import io.vertx.core.Verticle;
import io.vertx.core.spi.VerticleFactory;
/**
* A Verticle Factory that relies on a {@link ApplicationContext Spring Application Context}
* to get the requested Verticles. A verticleName must match a bean name/id within the Application
* Context.
* This factory relies on {@link ApplicationContextProvider} to provide the actual
* Spring Application Context.
* Verticles themselves should be prototype scope.
*
* @author Juan Velez
*/
public class SpringVerticleFactory implements VerticleFactory {
private static final String PREFIX = "spring";
public SpringVerticleFactory() {
}
/* (non-Javadoc)
* @see io.vertx.core.spi.VerticleFactory#prefix()
*/
@Override
public String prefix() {
return PREFIX;
}
/* (non-Javadoc)
* @see io.vertx.core.spi.VerticleFactory#blockingCreate()
*/
@Override
public boolean blockingCreate() {
return true;
}
/* (non-Javadoc)
* @see io.vertx.core.spi.VerticleFactory#createVerticle(java.lang.String, java.lang.ClassLoader)
*/
@Override
public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
verticleName = VerticleFactory.removePrefix(verticleName);
ApplicationContext ctx = getApplicationContext();
if (!ctx.containsBean(verticleName))
throw new IllegalArgumentException(String.format("No bean found for %s", verticleName));
if (!ctx.isPrototype(verticleName))
throw new IllegalArgumentException(String.format("Bean %s needs to be of Prototype scope", verticleName));
Verticle verticle = (Verticle) ctx.getBean(verticleName);
if (verticle==null)
throw new IllegalArgumentException(String.format("No bean found for %s", verticleName));
return verticle;
}
/**
* Gets the application context to be used for obtaining the verticles.
* @return The application context
*/
private ApplicationContext getApplicationContext() {
ApplicationContext appCtx = ApplicationContextProvider.getApplicationContext();
if (appCtx == null) {
throw new IllegalStateException("No Application Context Instance has been "
+ "set in ApplicationContextProvider.");
}
return appCtx;
}
}