Skip to content

Instantly share code, notes, and snippets.

@cenkc
Created March 15, 2021 00:37
Show Gist options
  • Save cenkc/049bca7cdeeff6e4b18430d0e80023f9 to your computer and use it in GitHub Desktop.
Save cenkc/049bca7cdeeff6e4b18430d0e80023f9 to your computer and use it in GitHub Desktop.
registering Spring beans manually at runtime
package com.cenkc.app.service;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.stereotype.Service;
/**
* created by Cenk Canarslan on 2021-03-15
*/
@Service
public class CustomBeanRegistrar implements BeanFactoryAware {
private ConfigurableBeanFactory configurableBeanFactory;
/**
* registering beans manually at runtime
*
* @param beanName
* @param bean
* @param <T>
*/
public <T> void registerBean(String beanName, T bean) {
configurableBeanFactory.registerSingleton(beanName, bean);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment