Implementation of Spring Ioc simulation and SpringIoc Simulation

Source: Internet
Author: User

Implementation of Spring Ioc simulation and SpringIoc Simulation

IOC: Let's tell you a story!

There is a cook who needs a certain seasoning (bean) when cooking a dish, but he doesn't have the seasoning (bean ), at this time, he must make a bottle of seasoning (bean. (This is like when we usually need objects: UserDao userdao = new UserDaoImpl) at this time, the cook's work had to be linked with the seasoning, which is called "coupling ". (In terms of coupling, Qualcomm says that I cannot survive without you .);

At this time, the control in IOC is reversed. It proposes to open up a warehouse (container) with a variety of condiments (beans) in it. When you need a certain seasoning (bean) only the name of the seasoning (beanName) can be obtained directly. The code is similar to this: (UserDao user = repository. get ("seasoning name"); then you can get the seasoning directly instead of making a bottle when you don't have it. This is the so-called transfer of control, it will produce seasoning (bean) work directly for the repository (container) to make (production );

Next, the dependency is injected, and it becomes more powerful. It proposes that the chef should open the bottle lid as long as there is a bottle (private UserDao userdao) (method: setUserDao (UserDao userdao) {this. userdao = userdao} is the set method provided. Add a label to the bottle to indicate the materials to be put (configure <property name = "userdao" in the xml file ", ref = "xxbean"), so you don't need to do anything at this time. The Repository (container) will automatically send someone to help you put the seasoning (bean) You need into the bottle; when you want to change another seasoning, you only need to change the label on the bottle to another one, such as pepper. (in this case, you need to change the bean of ref in the xml file ), dependency injection improves code flexibility. When you need to replace the implementation of classes, you don't need to modify them as long as you modify them in the xml configuration file;

Summary: The main objective of IOC is to achieve decoupling! Decoupling! Decoupling! The important thing is said three times. For example, I am a cook and I only cook food ~~ I am not a seasoning maker. I don't have that much to do with seasoning preparation. with the emergence of IOC, the cook just needs to do his own thing (cooking) with peace of mind, and the seasoning needs to be taken directly to the warehouse! In this way, the relationship between the cook and the seasoning is separated. This is the decoupling! Decoupling! Decoupling! Make the relationship between the two things less closely.

The main technology used to simulate the implementation of IOC is the reflection mechanism of java (the simulated architecture is divided into the dao layer, service layer, and controller layer ):

Note: you are welcome to give me some advice, and the younger brother is also studying. I'm sorry for the bad words ~

I. Write the dao class for testing:

Public interface IocDao {public void sayhello (); // an interface for testing}

2. Write the dao implementation class:

Public class IocDaoImpl implements IocDao {@ Override public void sayhello () {// TODO Auto-generated method stub System. out. println ("hello word"); // implement the methods in our dao interface }}

3. Compile the service class:

Public interface IocDaoService {public void sayhello (); // service class interface, which is the same as dao}

4. Compile the service implementation class:

Public class IocDaoServiceImpl implements IocDaoService {private IocDao iocDao; // create an interface. public IocDao getIocDao () {return iocDao;} // you can write the set method corresponding to the IocDao interface for dependency injection. // There are three methods for dependency injection: interface injection and constructor injection, set injection; // set injection public void setIocDao (IocDao iocDao) {this. iocDao = iocDao;} @ Override public void sayhello () {// TODO Auto-generated method stub iocDao. sayhello (); // call the interface method }}

5. write bean. xml configuration file. (here, you can think of I as IocDaoImpl, iocService as IocDaoServiceImpl, and iocDao as an attribute in IocDaoServiceImpl. The input parameter value of 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. Compile the factory interface.

// Simulate a BeanFactorypublic interface BeanFactory {public Object getBean (String beanName) implemented by ClassPathXmlApplicationContext );}

7. write ClassPathXmlApplicationContext to read the configuration file, and according to bean. the configuration object in xml generates various beans to complete the injection. (the most important part is the implementation principle of Ioc .)

// Simulate ClassPathXmlApplicationContext to read the configuration file public class ClassPathXmlApplicationContext implements BeanFactory {// define the map set to store beans. the bean id in xml corresponds to its instantiated object // <bean id = "I" class = "com. hck. dao. impl. iocDaoImpl "/> // store beans similarly. put ("I", new IocDaoImpl. map <String, Object> beans = new HashMap <String, Object> (); public ClassPathXmlApplicationContext (String xmlPath) {try {// create the SAXBuilder Object Parsing document SAXBuilder saxBuilder = new SAXBuilder (); // parse the parameters in build as a file path. document document = saxBuilder. build (xmlPath); // document. getRootElement (). getChildren ("bean") obtains all <bean> tag content List elements = document. getRootElement (). getChildren ("bean"); // traverses the <bean> object for (int I = 0; I <elements. size (); I ++) {// obtain the first <bean> label elements. get (0); Element element = (Element) elements. get (I); // obtain the <id> attribute in the <bean> tag, // <bean id = "I" class = "com. hck. dao. impl. iocDaoImpl "/> // that is, String beanName =" I "; String beanName = element. getAttributeValue ("id"); // same as String clazz = "com. hck. dao. impl. iocDaoImpl "; String clazz = element. getAttributeValue ("class"); // load the class Object and instantiate it. object object = new IocDaoImpl (); Object object = Class. forName (clazz ). newInstance (); // The object is IocDaoServiceImpl // Add them to the map set. The instantiated object can be directly obtained based on beanName. beans. put (beanName, object); // traverses the <property> word tag under the <bean> tag. // skip the first tag because it does not have a word tag. the second example is/<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 obtain <property name = "iocDao" ref = "I"> </property> </bean> Element element2 = (Element) elements2.get (j ); // equivalent to String propertyName = "iocDao"; String propertyName = element2.getAttributeValue ("name"); // equivalent to String refBean = "I"; String refBean = element2.getAttributeValue ("ref "); // It is equivalent to String propertyName = "IocDao"; // It is used to obtain the method name setIocDao for reflection and call propertyName = propertyName. substring (0, 1 ). toUpperCase () + propertyName. substring (1); // The methodName = "setIocDao"; String methodName = "set" + propertyName; // obtain the Key = "I" value in the Map set; I corresponds to the instantiated Object of IocDaoImpl // equivalent to Object object2 = IocDaoImpl; Object object2 = beans. get (refBean); // obtain the setIocDao method in the IocDaoServiceImpl 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 the method and input 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 () */@ Overridepublic Object getBean (String beanName) {// TODO Auto-generated method stub return beans. get (beanName );}}

8. Compile the test class

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 Results:

Here, the simulation of Ioc is over. If it is easy to use, you can click here for recommendations or click here for attention. What ~~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.