/** * Create a subclass of {@link AgentManagerService} depending on the cluster activation status. * * @return {@link AgentManagerService} */ @Bean(name = "agentManagerService") public AgentManagerService agentManagerService() { AgentManagerService createBean = (AgentManagerService) applicationContext.getAutowireCapableBeanFactory() .autowire(MockAgentManagerService.class, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); return createBean; }
private <T> T instantiate(Class<T> clazz) { return (T) beanFactory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_NO, false); } }
public class BeanInitializer implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> { private ApplicationContext context; private List<Class<?>> beanClasses; public void onApplicationEvent(final ContextRefreshedEvent event) { final AutowireCapableBeanFactory beanFactory = this.context.getAutowireCapableBeanFactory(); for (final Class<?> beanClass : this.beanClasses) { beanFactory.autowire(beanClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); } } public void setApplicationContext(final ApplicationContext context) throws BeansException { this.context = context; } public void setBeanClasses(final List<Class<?>> beanClasses) { this.beanClasses = beanClasses; } }
public static void main(String[] args) throws Exception { if (args.length != 1){ System.err.println("arguments: [bot class name]"); System.exit(1); } String botClass = args[0]; SpringApplication app = new SpringApplication( new Object[]{"classpath:/spring/app/botRunner.xml"} ); app.setWebEnvironment(false); ConfigurableApplicationContext applicationContext = app.run(args); Bot bot = null; //create a bot instance and auto-wire it AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory(); bot = (Bot) beanFactory.autowire(Class.forName(botClass), AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); Object botBean = beanFactory.initializeBean(bot, "theBot"); bot = (Bot) botBean; //the bot also needs a trigger so its act() method is called regularly. // (there is no trigger bean in the context) if (bot instanceof TriggeredBot){ PeriodicTrigger trigger = new PeriodicTrigger(5000, TimeUnit.MILLISECONDS); trigger.setInitialDelay(1000); ((TriggeredBot) bot).setTrigger(trigger); } BotManager botManager = (BotManager) applicationContext.getBean("botManager"); //adding the bot to the bot manager will cause it to be initialized. //at that point, the trigger starts. botManager.addBot(bot); }
return bean; } else { bean = autoWiringFactory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false); bean = autoWiringFactory.initializeBean(bean, bean.getClass().getName()); return autoWireBean(bean, autoWiringFactory);