The factory pattern spring ioc

spring three modules, ioc is the foundation, the biggest advantage is decoupling. Two prominent features, inversion and dependency injection (in fact, is assigned).

Reverse the underlying idea to use the factory pattern. Then we opened with his veil.

 

Step 1: Create our traditional dao layer

public interface TestIocDao {
    void save();
}
public class TestIocDaoImpl implements TestIocDao {
    @Override
    public void save() {
        System.out.println("保存到数据库");
    }
}

Step 2: Create our traditional service layer

public interface TestIocService {
    public void save();
}
public class TestIocServiceImpl implements TestIocService {

    private TestIocDao iocDao = (TestIocDao)MyBeanFactory.getBean("testIocDao");

    @Override
    public void save() {
        iocDao.save();
    }
}

Step 3: Create our factory

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;
    }
}

Step Four: Create a simulated xml, txt file

testIocDao=com.pian.dao.impl.TestIocDaoImpl
testIocService=com.pian.service.impl.TestIocServiceImpl

Step 5: Create a test case

public class TestIocFactory {

    private TestIocService iocService = (TestIocService)MyBeanFactory.getBean("testIocService");

    @Test
    public void test1(){
        iocService.save();
    }
}

Summary: The code is relatively simple, do not explain, written ,, can deepen a clearer understanding of the spring loaded mechanism, you can also try it ....

 

Published 62 original articles · won praise 5 · views 30000 +

Guess you like

Origin blog.csdn.net/yingcly003/article/details/104255593