Java programmers from stupid birds to cainiao (sixty-eight) Talk about spring (ii) self-built simulation of spring

Source: Internet
Author: User



Before learning spring, we can simulate a spring by ourselves based on the characteristics of spring. That is to say, we will not use spring to achieve the effect of spring. This example mainly implements the IOC function of spring.


Click to download source code: Use ghost


First, we define the Dao, service, and entity we use:

Student. Java:

Package COM. BZU. entity; public class student {private int ID; private string name; private string address; * ****************** the set and get methods are omitted}

Because spring advocates interface-oriented programming, before we write the specific implementation of the DaO layer and the service layer, we first define the interface and let us implement the interface. The interface code is very simple and will not be pasted here.

StudentdaoImp.javapublic class StudentDaoImp implements StudentDao {public void add(Student stu) {System.out.println("stu is saved");}}

Studentserviceimp. Java

public class StudentServiceImp implements StudentService {StudentDao stuDao=null;public StudentDao getStuDao() {return stuDao;}public void setStuDao(StudentDao stuDao) {this.stuDao = stuDao;}@Overridepublic void add(Student stu) {stuDao.add(stu);}}

It should be noted that here we simulate spring, mainly to simulate the IOC function in spring, so here we need to define Dao instances in the service layer, of course, not new, we can inject the DaO layer here through Spring IoC. Do not forget to provide set for Dao. Get method, because the bottom layer of IOC is actually implemented by using the reflection mechanism. It injects Dao into it. In fact, the bottom layer is reflected through the set.

Well, after the DaO layer, service layer, and entity are defined, everything is ready. The next step is to define our own classpathxmlapplicationcontext class, when we New his object, he loads the configuration file and injects our Dao operation into our service layer. In spring, the classpathxmlapplicationcontext class implements the beanfactory interface, here we also define a beanfactory interface. In fact, this interface does not have any specific function. We just want to simulate spring. Before defining this interface and implementation class, let's take a look at how the XML we need is written. Next we will take a look at the configuration of beans. xml:

Beans. xml:

<beans><bean id="stuDao" class="com.bzu.dao.imp.StudentDaoImp" /><bean id="stuService" class="com.bzu.service.imp.StudentServiceImp" ><property name="stuDao" bean="stuDao"/></bean></beans>

Seeing this, I believe everyone can feel that this configuration file is too simple, not as complicated as spring configuration. Of course, we just implement one of the functions, spring provides many powerful functions, and configuration is cumbersome. I believe that the above Code can be understood without my explanation.

Now, we have read the configuration file. Next, let's take a look at how our spring container-classpathxmlapplicationcontext is implemented. Let's first take a look at its interface definition:

Beanfactory. Java:

public interface BeanFactory {public Object getBean(String id);}

As we can see, the interface is actually very simple, and a getbean method is defined. Let's take a look at the specific implementation class:

Classpathxmlapplicationcontext. Java

Public class classpathxmlapplicationcontext implements beanfactory {private Map <string, Object> beans = new hashmap <string, Object> (); Public classpathxmlapplicationcontext () throws exception, 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 disk for (INT I = 0; I <list. size (); I ++) {element = (element) list. get (I); string id = element. getattributevalue ("ID"); string clazz = element. getattributevalue ("class"); object o = Class. forname (clazz ). newinstance (); system. out. println (ID); system. out. println (clazz); beans. put (ID, O); For (element propertyelement: (list <element>) element. getchildren ("property") {string name = propertyelement. getattributevalue ("name"); // userdaostring bean = propertyelement. getattributevalue ("Bean"); // uobject beanobject = beans. get (bean); // userdaoimpl instancestring methodname = "set" + name. substring (0, 1 ). touppercase () + name. substring (1); system. out. println ("method name =" + methodname); method M = O. getclass (). getmethod (methodname, beanobject. getclass (). getinterfaces () [0]); M. invoke (O, beanobject) ;}}@ overridepublic object getbean (string ID) {return beans. get (ID );}}

The Code has been posted. I don't know if you understand it. The following code is explained:

First, we define a container Map <string, Object> beans. This container is used to install the beans parsed from the configuration file. Why should we use the map type, I guess you can also guess that every bean in our configuration file has an ID as its unique identity. We store this ID in the key of the map, and then the value is loaded with our specific bean object. After talking about this container, let's take a look at the classpathxmlapplicationcontext constructor. This constructor is the core of our spring container management. The first half of this constructor is the JDOM parsing method, parse the beans in XML one by one, and then put the parsed beans in our Bean container. If this Code cannot be understood, you have to look at the JDOM parsing XML. Okay, let's take a look at the construction method below. The second half is mainly to check whether the bean needs to be injected in the bean while parsing the bean in the configuration file, if so, he will get the name of the bean to be injected through the property attributes in them, construct the set method, and call the Set Method for bean injection through reflection, in this way, the bean we need will be injected in. If you cannot understand this code, you can only look at the reflection knowledge. Finally, let's take a look at the getbean implementation interface. In fact, this method is very simple. It is to extract the corresponding bean from the bean container Based on the provided bean ID.

Well, all the things we need are defined. Let's test the following to see if we can automatically inject the DaO layer that we need into our imitation spring.

public static void main(String[] args) throws Exception {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();Student stu = new Student();StudentService service = (StudentService) context.getBean("stuService");service.add(stu);}

Run the code and the console outputs:

Com. BZU. Service. Imp. studentserviceimp

Method Name = setstudao

Stu is saved

Well, the successful injection has ended. At this point, the imitation spring has ended. In the next article, we will begin to have a comprehensive and in-depth understanding of spring, so stay tuned.

Related Article

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.