com.blade.ioc.SimpleIoc Maven / Gradle / Ivy
package com.blade.ioc;
import com.blade.ioc.bean.BeanDefine;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
/**
* The default IOC container implementation
*
* @author biezhi
* @since 1.5
*/
@Slf4j
public class SimpleIoc implements Ioc {
private final Map pool = new HashMap<>(32);
/**
* Add user-defined objects
*/
@Override
public void addBean(Object bean) {
addBean(bean.getClass().getName(), bean);
}
/**
* Add user-defined objects
*/
@Override
public void addBean(String name, Object bean) {
BeanDefine beanDefine = new BeanDefine(bean);
addBean(name, beanDefine);
// add interface
Class>[] interfaces = beanDefine.getType().getInterfaces();
if (interfaces.length > 0) {
for (Class> interfaceClazz : interfaces) {
this.addBean(interfaceClazz.getName(), beanDefine);
}
}
}
/**
* Update BeanDefine
*/
@Override
public void setBean(Class> type, Object proxyBean) {
BeanDefine beanDefine = pool.get(type.getName());
if (beanDefine != null) {
beanDefine.setBean(proxyBean);
} else {
beanDefine = new BeanDefine(proxyBean, type);
}
pool.put(type.getName(), beanDefine);
}
/**
* Register @Bean marked objects
*/
@Override
public T addBean(Class type) {
Object bean = addBean(type, true);
return type.cast(bean);
}
@Override
public T getBean(Class type) {
Object bean = this.getBean(type.getName());
try {
return type.cast(bean);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Object getBean(String name) {
BeanDefine beanDefine = pool.get(name);
if (beanDefine == null) {
return null;
}
return beanDefine.getBean();
}
@Override
public List getBeanDefines() {
return new ArrayList<>(pool.values());
}
@Override
public BeanDefine getBeanDefine(Class> type) {
return this.getBeanDefine(type, true);
}
@Override
public List