春3つのモジュールは、IOCが最大の利点は、デカップリングされ、基礎となるものです。二つの顕著な特徴、反転と依存性注入(実際には、割り当てられています)。
ファクトリパターンを使用する基本的な考え方を逆にします。その後、我々は彼のベールで開かれました。
ステップ1:私たちの伝統的なDAO層を作成します。
public interface TestIocDao {
void save();
}
public class TestIocDaoImpl implements TestIocDao {
@Override
public void save() {
System.out.println("保存到数据库");
}
}
ステップ2:私たちの伝統的なサービス層を作成します。
public interface TestIocService {
public void save();
}
public class TestIocServiceImpl implements TestIocService {
private TestIocDao iocDao = (TestIocDao)MyBeanFactory.getBean("testIocDao");
@Override
public void save() {
iocDao.save();
}
}
ステップ3:工場を作成します。
public class MyBeanFactory {
private static Properties properties = new Properties();
static {
InputStream inputStream = MyBeanFactory.class.getResourceAsStream("/iocBean.properties");
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getBean(String name){
String className = properties.getProperty(name);
try {
return Class.forName(className).newInstance();
} catch (InstantiationException |IllegalAccessException|ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
ステップ4:シミュレートされたXMLを作成し、TXTファイル
testIocDao=com.pian.dao.impl.TestIocDaoImpl
testIocService=com.pian.service.impl.TestIocServiceImpl
ステップ5:テストケースを作成します。
public class TestIocFactory {
private TestIocService iocService = (TestIocService)MyBeanFactory.getBean("testIocService");
@Test
public void test1(){
iocService.save();
}
}
要約:コードは比較的簡単ですが、......、あなたもそれを試すことができ、スプリングロードされたメカニズムをより明確に理解を深めでき,,書かれ、説明されていません。