依存注入のシミュレーション
依存注入と制御反転(DI&IoC)
1依存注入のシミュレーション
1依存注入のシミュレーション
//
public class Business implements IBeanAware {
private IWriter writer;
public Business() {
}
// type1 Constructor Injection
public Business(IWriter writer) {
this.writer = writer;
}
// type2 Interface Injection
@Override
public void injectBean(Object dependcy) {
writer = (IWriter) dependcy;
}
// type3 Setter Injection
public void setWriter(IWriter writer) {
this.writer = writer;
}
public void save() {
writer.write();
}
public static void main(String[] args) throws Exception {
BeanFactory applicationContext = BeanFactory.getInstance();
Business biz = (Business)applicationContext.getBean("business");
biz.save();
}
}
//
interface IWriter {
public void write();
}
class FileWriter implements IWriter {
@Override
public void write() {
System.out.println("write into file.");
}
}
class ConsoleWriter implements IWriter {
@Override
public void write() {
System.out.println("write into console.");
}
}
// IoC ,
@SuppressWarnings("unchecked")
class BeanFactory {
private static BeanFactory applicationContext;
private Object bean;
private Properties props;
private BeanFactory() throws Exception {
props = new Properties();
props.load(new FileInputStream("bean.properties"));
}
public static BeanFactory getInstance() throws Exception {
if (applicationContext == null)
applicationContext = new BeanFactory();
return applicationContext;
}
public Object getBean(String beanName) throws Exception {
IWriter writer = (IWriter) Class.forName(props.getProperty("writer"))
.newInstance();
Class<Business> claz = (Class<Business>) Class.forName(props
.getProperty(beanName));
Constructor<Business> c = claz.getConstructor(IWriter.class);
if (c.getParameterTypes().length != 0) {
bean = c.newInstance(writer);
System.out.println("type1 Constructor Injection");
} else if (bean instanceof IBeanAware) {
bean = claz.newInstance();
IBeanAware aware = (IBeanAware)bean;
aware.injectBean(writer);
System.out.println("type2 Interface Injection");
} else {
bean = claz.newInstance();
Method m = claz.getDeclaredMethod("setWriter", IWriter.class)
m.invoke(bean, writer);
System.out.println("type3 Setter Injection");
}
return bean;
}
}
interface IBeanAware {
public void injectBean(Object dependcy);
}
bean.properties
business = org.powersoft.spring.demo.Business
writer = org.powersoft.spring.demo.FileWriter
#writer = org.powersoft.spring.demo.ConsoleWriter