About IOC: Let's tell a story!
There was a cook who needed some kind of spice when he was cooking a dish, but he just didn't have that bottle of spice. At that time, he had to make a bottle of spice. (It's like when we need objects: UserDao, userdao=new UserDaoImpl.) At this point, the cook's job has to be linked to the production of condiments, which is called coupling. (Coupling Qualcomm, in other words, I can't live without you.) ;
At this point, the IOC's control is reversed. It proposes to open up a warehouse (container) with a variety of spices (beans). When you need a certain kind of spices (beanName), you can get them directly. The code is similar to this: (UserDao user = warehouse. get("spice name"); so you can get the spices directly. You don't have to wait until you don't have time to make a bottle. This is the so-called transfer of control, it will produce spices (beans) directly to the warehouse (containers) to produce (production);
Next the dependency injection comes out, and it's even more powerful. It suggests that the chef should just have a private User Dao userdao and open the cap of the bottle (method: set User Dao userdao {this. userdao = userdao} and then label the bottle with a label indicating what material to put (configure < property name= "us" in the xml file). Erdao ", ref =" xxbean ", then you don't need to do anything at this time, the warehouse (container) will automatically send someone to help you put the required seasoning (beans) into the bottle; when you want to change another seasoning, just change the label on the bottle to something else like pepper (then change ref beans in the xml file), and rely on injection to improve the code's flexibility. Active, when you need to replace the implementation of the class, you don't need to modify it, just modify it in the xml configuration file.
Summarize my conclusion: The main purpose of IOC is to achieve decoupling! Decoupling! Decoupling! I am a cook. I only cook. I don't cook spices. I don't make spices. I don't have much to do with making spices. So the relationship between chef and condiment production is separated, which is decoupling! Decoupling! Decoupling! Make the relationship between the two things less intimate.
To simulate the implementation of IOC, the main technology used is the reflection mechanism of java (simulated architecture is divided into dao layer, service layer, controller layer):
Note: Welcome your advice, younger brother is also learning, not a lot of inclusive.~
1. Write dao classes for testing:
public interface IocDao { public void sayhello(); //An interface for testing }
2. Write the implementation class of dao:
public class IocDaoImpl implements IocDao { @Override public void sayhello() { // TODO Auto-generated method stub System.out.println("hello word");//Achieving our dao Method in Interface } }
3. Write the service class:
public interface IocDaoService { public void sayhello();//Business Class Interface,Here we go. dao equally }
4. Write the implementation class of service:
public class IocDaoServiceImpl implements IocDaoService { private IocDao iocDao; //Create an interface. public IocDao getIocDao() { return iocDao; } //To write IocDao Interface Corresponding set Method for Dependency Injection //There are three ways of dependency injection: interface injection, construction method injection. set injection; //Here is set injection public void setIocDao(IocDao iocDao) { this.iocDao = iocDao; } @Override public void sayhello() { // TODO Auto-generated method stub iocDao.sayhello();//Call interface methods } }
5. Write the bean.xml configuration file. (Here I can be seen as the IocDaoImpl class, iocService as IocDaoServiceImpl,iocDao is an attribute in IocDaoServiceImpl, and the parameter value passed in by this attribute is "i";
<beans> <bean id="i" class="com.hck.dao.impl.IocDaoImpl"/> <bean id="iocService" class="com.hck.service.impl.IocDaoServiceImpl"> <property name="iocDao" ref="i"></property> </bean> </beans>
6. Write factory interface.
//simulation ClassPathXmlApplicationContext An interface for implementation BeanFactory public interface BeanFactory { public Object getBean(String beanName); }
7. Write ClassPath Xml Application Context to read the configuration file, and generate various beans according to the configuration objects in bean.xml to complete the injection work. (The most important part of Ioc implementation principle), each word has a comment.
//simulation ClassPathXmlApplicationContext To read the configuration file public class ClassPathXmlApplicationContext implements BeanFactory { //Definition map Collection to store bean.xml Li bean Of id Instance objects corresponding to them //<bean id="i" class="com.hck.dao.impl.IocDaoImpl"/> //So similar storage bean.put("i",new IocDaoImpl());this look. Map<String, Object> beans=new HashMap<String,Object>(); public ClassPathXmlApplicationContext(String xmlPath){ try { //Establish SAXBuilder Object parsing document SAXBuilder saxBuilder = new SAXBuilder(); //analysis build The parameter in the file is a file path.. Document document = saxBuilder.build(xmlPath); //document.getRootElement().getChildren("bean")Get all<bean>Label content List elements = document.getRootElement().getChildren("bean"); //ergodic<bean>object for (int i = 0; i < elements.size(); i++) { //Get the first<bean>Label elements.get(0); Element element = (Element) elements.get(i); //Obtain<bean>Inside the label<id>Attribute, //<bean id="i" class="com.hck.dao.impl.IocDaoImpl"/> //Namely String beanName="i"; String beanName = element.getAttributeValue("id"); //Ditto String clazz="com.hck.dao.impl.IocDaoImpl"; String clazz = element.getAttributeValue("class"); //Load class objects and instantiate them.Object object=new IocDaoImpl(); Object object = Class.forName(clazz).newInstance();//object yes IocDaoServiceImpl //Add them to map In the collection,The following can be based on beanName Get instantiated objects directly. beans.put(beanName, object); //ergodic<bean>Under the label<property>Word labels. //The first tag has no word tag, so skip it directly..The second is an example. //<bean id="iocService" class="com.hck.service.impl.IocDaoServiceImpl"> //<property name="iocDao" ref="i"></property></bean> List elements2 = element.getChildren("property"); for (int j = 0; j < elements2.size(); j++) { //Here we will get<property name="iocDao" ref="i"></property></bean> Element element2 = (Element) elements2.get(j); //Amount to String propertyName="iocDao"; String propertyName = element2.getAttributeValue("name"); //Amount to String refBean="i"; String refBean = element2.getAttributeValue("ref"); //Amount to String propertyName="IocDao"; //The purpose is to get the name of a method. setIocDao,Used for reflection calls propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); //There methodName="setIocDao"; String methodName = "set" + propertyName; //Obtain Map In the collection Key="i"Value;i The corresponding is IocDaoImpl Instance object //Amount to Object object2 =IocDaoImpl; Object object2 = beans.get(refBean); //Obtain IocDaoServiceImpl In the method setIocDao Method. //The first method is the method name, and the second parameter is the parameter type of the method.. Method method = object.getClass().getDeclaredMethod(methodName, object2.getClass().getInterfaces()); //Call methods and pass in parameters to complete dependency injection. method.invoke(object, object2); } } // String beanName=document.getElementById(id).attributes().get("class"); // Object object=Class.forName(beanName).newInstance(); // return object; } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } } /* (non-Javadoc) * @see com.hck.ioc.BeanFactory#getBean() */ @Override public Object getBean(String beanName) { // TODO Auto-generated method stub return beans.get(beanName); } }
VIII. Writing Test Classes
public class Ioc { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("src/bean.xml"); IocDaoService ids=(IocDaoService)applicationContext.getBean("iocService"); ids.sayhello(); } }
9. Display the results:
At this point, the Ioc simulation is over. Friends who find it easy and useful can click on the recommendation or click on the attention. Meme Da ~ ~