1. Create the @autowried annotation

    @Retention(retentionPolicy.runtime) /** * retentionPolicy.source retained in. Java when compiled to class will be discarded * retentionPolicy.class The default lifecycle * retentionPolicy. RUNTIME is not only saved to the class file but also exists after the JVM loads the class file @target (elementType.field) // Works on attributes /** * elementType. TYPE Interface class enumeration * elementType. FIELD FIELD enumeration constant * elementType. METHOD METHOD PARAMETER Method argument * ElementType.CONSTRUCTOR CONSTRUCTOR * ElementType.LOCAL_VARIABLE Local variable * ANNOTATION_TYPE */ / @inherited // Public @interface Autowired {} Whether to document (indicating that the annotation will be included in javadoc)Copy the code
  2. Creating a Test Controller

    public class TestController { @Autowired private TestService testService; public TestService getTestService() { return testService; }}Copy the code
  3. Create test Service

        public class TestService {}
    Copy the code
  4. Code implementation and testing

    public class AutowiredTest { public static void main(String[] args) { TestController testController = new TestController(); // reflection gets Class<? extends TestController> clazz = testController.getClass(); // Get all property values and traverse stream.of (clazz.getDeclaredFields()).foreach (field -> {// Determine if the current property uses an Autowired annotation = field.getAnnotation(Autowired.class); if (annotation ! = null){ field.setAccessible(true); // Private attributes can be accessed // get the type to create the corresponding object Class<? > type = field.getType(); O = type.newinstance (); / / into the field. The set (testController, o); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }}}); / / print injected class output address values Represents a successful System. Out. Println (testController. GetTestService ()); }}Copy the code
  5. The results