@zenbeni answered this question, but I want to tell you about my implementation, it is difficult to make a nozzle / bolts like spring beans. But to use other spring spring beans inside your pins / bolts, you can declare a global variable, and in your execution method, checking the whtether variable is null or not. If it is zero, you should get a bean from the application context. Create a class that contains the beans initialization method if it is not already initialized. See the ApplicationContextAware interface for more information (reusing Spring bean).
Code example:
Bolt class:
public class Class1 implements IRichBolt{ Class2 class2Object; public void prepare() { if (class2Object== null) { class2Object= (Class2) Util .initializeContext("class2"); } } }
Util class to initialize beans, if not already initialized:
public class Util{ public static Object initializeContext(String beanName) { Object bean = null; try { synchronized (Util.class) { if (ApplicationContextUtil.getAppContext() == null) { ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml"); bean = ApplicationContextUtil.getAppContext().getBean( beanName); } else { bean = ApplicationContextUtil.getAppContext().getBean( beanName); } } } catch (Exception e) { e.printStackTrace(); } return bean; } }
Listener for changing application context:
@Component public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext appContext; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { appContext = applicationContext; } public static ApplicationContext getAppContext() { return appContext; } }
Note. Each worker will initialize the spring context as it works in different JVMs.
UPDATE
If you want to use the spring bean class in which you have previously assigned values, try this,
Note. Passing the current class to the Bolt constructor
A class (topology creation class) that already contains values:
public class StormTopologyClass implements ITopologyBuilder, Serializable { public Map<String, String> attributes = new HashMap<String, String>(); TopologyBuilder builder=new TopologyBuilder(); builder.setBolt("Class1",new Class1(this)); builder.createTopology(); }
Bolt using the single argument constructor:
public class Class1 implements IRichBolt{ StormTopologyClass topology; public Class1 (StormTopologyClass topology) { this.topology = topology; } }
Now you can use the variable attributes and values ββin the bolt class.