Simulate spring-simple implementation of spring IOC

Source: Internet
Author: User

I. Preface

IOC (Inverse of control)-control inversion. spring's IOC implementation principle is to use the Java reflection mechanism and act as the factory role to complete object assembly and injection.

II. Implementation Details

Attached to the structure of a class, this example needs to import jdom. jar and junit. jar



<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + CqLZINPDu6dCZWFuPC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> package com. zdp. model; // User class public class User {private String userName; private String password; public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}}② UserService

package com.zdp.service;import com.zdp.dao.UserDao;import com.zdp.model.User;public class UserService {private UserDao userDao;public void add(User user) {userDao.save(user);}public UserDao getUserDao() {return userDao;}public void setUserDao(UserDao userDao) {this.userDao = userDao;}}
③ UserDao

package com.zdp.dao;import com.zdp.model.User;public class UserDao {public void save(User user) {System.out.println("user saved!");}}
④ Bean Factory Interface

Package com. zdp. spring; // Bean Factory interface public interface BeanFactory {public Object getBean (String id );}
⑤ Bean factory implementation

Package com. zdp. spring; import java. lang. reflect. method; import java. util. hashMap; import java. util. list; import java. util. map; import org. jdom. document; import org. jdom. element; import org. jdom. input. SAXBuilder; // Bean factory implementation class public class ClassPathXmlApplicationContext implements BeanFactory {private Map
 
  
Beans = new HashMap
  
   
(); Public ClassPathXmlApplicationContext () throws Exception {SAXBuilder sb = new SAXBuilder (); Document doc = sb. build (this. getClass (). getClassLoader (). getResourceAsStream ("beans. xml "); // construct the document object Element root = doc. getRootElement (); // obtain the root element HDList = root. getChildren ("bean"); // obtain all elements named bean for (int I = 0; I <list. size (); I ++) {Element element = (Element) list. get (I); String id = element. getAttributeValue ("id"); String clazz = element. getAttributeValue ("class"); Object beanObj = Class. forName (clazz ). newInstance (); // obtain the object beans through reflection. put (id, beanObj); // Save the object to the Bean factory for (Element propertyElement: (List
   
    
) Element. getChildren ("property") {String name = propertyElement. getAttributeValue ("name"); // name = "userDao" String bean = propertyElement. getAttributeValue ("bean"); // bean = "userDao" Object injectObject = beans. get (bean); // get UserDaoString methodName = "set" + name from Bean factory. substring (0, 1 ). toUpperCase () + name. substring (1); // setUserDaoMethod method = beanObj. getClass (). getMethod (methodName, injectObject. getClass (); method. invoke (beanObj, injectObject); // set injection UserDao Object }}public Object getBean (String id) {return beans. get (id );}}
   
  
 

Here is the core code. Of course, in actual situations, this section is much more complicated. For example, one bean can reference another bean, you can also have multiple configuration files and load configuration files in multiple ways. However, the principle is still using the Java reflection mechanism.

⑥ Configuration file

 
  
  
   
  
 
7. Unit Test

Package com. zdp. service; import org. junit. test; import com. zdp. model. user; import com. zdp. spring. beanFactory; import com. zdp. spring. classPathXmlApplicationContext; // test code: public class UserServiceTest {@ Testpublic void testAdd () throws Exception {BeanFactory applicationContext = new ClassPathXmlApplicationContext (); // obtain the context UserService service = (UserService) applicationContext. getBean ("userService"); // Spring assembles BeanUser user = new User (); user. setUserName ("zhangsan"); user. setPassword ("123456"); service. add (user); // Save the user to the database }}

Iii. Summary

The above is just a simple simulation of the implementation of spring's IOC. Although it only completes a small part of spring's dependency injection, it still shows the application of the Java reflection mechanism in spring, it is helpful for beginners to understand IOC.


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.