1. 程式人生 > 其它 >自己寫一個註解 代替@Autowire

自己寫一個註解 代替@Autowire

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface MyAutowire {
}
public class TestController {

    @MyAutowire
    private TestService testService;

    public void testControllerMethod(){
        testService.testserviceMethod();
    }

}
public
class TestService { public void testserviceMethod(){ System.out.println("我是service"); } }
public class Test {

    public static void main(String[] args) {
        TestController testController=new TestController();
        Class clazz=testController.getClass();
        Field[] fields 
=clazz.getDeclaredFields(); for(Field field:fields){ Annotation annotation= field.getAnnotation(MyAutowire.class); if(annotation!=null){ Class type=field.getType(); try { //必須設定為可訪問 否則會報錯 field.setAccessible(true
); Object o=type.newInstance(); //拿到這個屬性 向物件的這個屬性設定值 field.set(testController,o); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
      
     //可以成功輸出 service的列印的 我是service testController.testControllerMethod(); } }