其他分享
首页 > 其他分享> > spring面试

spring面试

作者:互联网

spring流程图

https://www.processon.com/view/link/5feef2e0e401fd661a0b06fc

手写AutoWired注解,了解反射创建对象

https://github.com/Q2021/spring/tree/master/src

package org.example.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoWired {
}
package org.example.controller;

import org.example.annotation.AutoWired;
import org.example.service.UserService;

public class UserController {

    @AutoWired
    private UserService userService;

    public UserService getUserService() {
        return userService;
    }
    
}
@Test
    public void test02() {
        UserController userController = new UserController();
        Class<? extends UserController> clazz = userController.getClass();
        //获取所有属性值
        Stream.of(clazz.getDeclaredFields()).forEach(field -> {
            AutoWired annotation = field.getAnnotation(AutoWired.class);
            if (annotation != null) {
                field.setAccessible(true);
                //获取属性类型
                Class<?> type = field.getType();
                try {
                    Object o = type.newInstance();
                    field.set(userController, o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println(userController.getUserService());
    }

 

标签:AutoWired,spring,org,field,面试,import,userController,annotation
来源: https://www.cnblogs.com/Q2021/p/14220536.html