Spring IOC analog implementation manual function (based on javaConfig style)

  The following text refers specifically to spring spring Framework project, without other: Cloud as spring and the like.

  As the spring has just begun to study the source code white, spring for one of the IOC two core functions, although general understanding of Bean registered with the instantiation process, PostProcessors to instantiate the bean and other interventions, or feel they have to hand at practice IOC function, whether they be the source of the spring with the initial entry under test. The simulation-based annotation style, but also more in line with current mainstream development trend of spring. Because it is done manually, of course, it can not be springboot build the project using eclipse idea or create a common web project right. According to the order to develop it.

  Some notes from the definition of

  Based on the configuration of the familiar style of children's shoes all know, spring inside the most popular notes @ ComponentScan, @ Component and @Autowired. He said a little under three annotations role, @ ComponentScan: For scanning Bean under the specified directory. @Component: a general description of pojo, informing spring pojo this context needs to be managed by the container spring, i.e. the spring bean. @Autowired: Bean automatically inject property, the default is injected in accordance with bytype. Then, copy or imitate, define the following three corresponding annotations

 1 @Retention(RetentionPolicy.RUNTIME)
 2 public @interface MyAutowired {
 3     String value() default "";
 4 }
 5 
 6 @Retention(RetentionPolicy.RUNTIME)
 7 public @interface MyComponent {
 8     String value();
 9 }
10 
11 @Retention(RetentionPolicy.RUNTIME)
12 public @interface MyComponentScan {
13     String value();
14 }

  Note that each custom annotation should at least add annotations @Retention, and value is specified runtime. @Retention is used to modify the annotated notes, it is a meta-annotation. RetentionPolicy.RUNTIME: Notes not only be saved to a file class, after class load jvm file still exists.

  Define several pojo

  Configuration class is a MyConfigure, for specifying the scan path, a single function. Add comments @MyComponentScan custom. Com.entity scan type in the specified path.

1 package com.entity;
2 import com.annotate.MyComponentScan;
3 
4 @MyComponentScan("com.entity")
5 public class MyConfigure {
6 
7 }

  Two simple entity class Order and User, plus custom annotation @MyComponent. There is a member of the Order which attributes User, add comments @MyAutowired.

 1 package com.entity;
 2 
 3 import com.annotate.MyAutowired;
 4 import com.annotate.MyComponent;
 5 
 6 @MyComponent("myComponent")
 7 public class Order {
 8     @MyAutowired
 9     private User user;
10 
11     public void print(){
12         System.out.println("This is order");
13     }
14 
15     public void printUser(){
16         this.user.printMessage();
17     }
18 }
 1 package com.entity;
 2 
 3 import com.annotate.MyComponent;
 4 
 5 @MyComponent("myComponent")
 6 public class User {
 7     public void print(){
 8         System.out.println("This is user");
 9     }
10 
11     public void printMessage(){
12         System.out.println("This is user from order");
13     }
14 }

  spring simulation context

  spring context MySpringApplicationContext implemented mainly includes a registration path of the scanning method and Bean getBean process, also comprising a key member property map, the context is registered and instantiated Bean for storage.

 1 package com.myspring;
 2 
 3 import com.annotate.MyAutowired;
 4 import com.annotate.MyComponent;
 5 import com.annotate.MyComponentScan;
 6 
 7 import java.io.File;
 8 import java.lang.reflect.Field;
 9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.Map;
12 
13 public class MySpringApplicationContext {
14     /**
15      * 存放bean的map(模仿spring beanfactory 中的map)
16      */
17     private HashMap<String,Object> beanFactoryMap;
18 
19     public MySpringApplicationContext(Class clazz){
20         beanFactoryMap = new HashMap<String, Object>();
21         this.packageScan(clazz);
22     }
23 
24 
25     public void packageScan(Class configureClazz){
26         //获取扫描路径
27         MyComponentScan myComponentScan = (MyComponentScan) configureClazz.getAnnotation(MyComponentScan.class);
 28          IF (myComponentScan == null ) {
 29              return ;
 30          }
 31 is          / ** 
32           * directory acquired to be scanned
 33 is           * / 
34 is          String the packageName = myComponentScan.value ();
 35          String = rootPath the this .getClass (). the getResource ( "/" ) .getPath ();
 36          String PackagePath packageName.replaceAll = (, "/" "\\." );
 37 [          / ** 
38 is           * absolute address acquired scan list
 39           * / 
40          String classFilePath = rootPath + PackagePath;
41         File file = new File(classFilePath);
42         String[] files = file.list();
43         if(files != null && files.length>0){
44             for(String subFile:files){
45                 try {
46                     String beanName = subFile.split("\\.")[0];
47                     Class clazz = Class.forName(packageName +"."+ beanName);
48                     if(clazz.isAnnotationPresent(MyComponent.class)){
49                         Object object = clazz.newInstance();
50                         beanFactoryMap.put(beanName.toLowerCase(),object);
51                     }
52                 } catch (Exception e) {
53                     e.printStackTrace();
54                 }
55             }
56         }
57         //处理注入的问题(模拟@Autowired)
58         if(!beanFactoryMap.isEmpty()){
59             Iterator iterator = beanFactoryMap.entrySet().iterator();
60             while (iterator.hasNext()){
61                 try {
62                     Map.Entry entry = (Map.Entry) iterator.next();
63                     Class clazz = entry.getValue().getClass();
64                     Field[] fields = clazz.getDeclaredFields();
65                     if(fields != null && fields.length > 0){
66                         for(Field field:fields){
67                             field.setAccessible(true);
68                             MyAutowired myAutowired = field.getAnnotation(MyAutowired.class);
69                             if(myAutowired != null){
70                                 field.set(entry.getValue(),beanFactoryMap.get(field.getName()));
71                             }
72                         }
73                     }
74                 } catch (Exception e) {
75                     e.printStackTrace();
76                 }
77             }
78         }
79 
80     }
81 
82     public Object getBean(String beanName){
83         return this.beanFactoryMap.get(beanName);
84     }
85 
86 }

  test

  Bean's main test content is successfully registered and instantiated, Bean successful implantation.

 1 package com.test;
 2 
 3 import com.entity.User;
 4 import com.myspring.MySpringApplicationContext;
 5 import com.entity.MyConfigure;
 6 import com.entity.Order;
 7 public class Test {
 8     public static void main(String[] args) {
 9         MySpringApplicationContext mySpringApplicationContext = new MySpringApplicationContext(MyConfigure.class);
10         User user = (User) mySpringApplicationContext.getBean("user");
. 11          user.print ();
 12 is          Order Order = (Order) mySpringApplicationContext.getBean ( "Order" );
 13 is          order.print ();
 14          / ** 
15           * Order for verifying whether the successfully injected User object
 16           * / 
17          order.printUser ();
 18 is      }
 . 19 }

  The results output

1 This is user
2 This is order
3 This is user from order

  The above is the whole process of manually implement spring IOC function, of course, this is only a fur coat spring mechanism, hope to have the desire to learn, but not yet implemented understand the source of spring shoes to help start a discussion. Limited strength, welcomed the experts colleagues criticized the correction.

 

Guess you like

Origin www.cnblogs.com/zhycareer/p/11891962.html