【Spring系列】- 手写模拟Spring框架( 四 )

运行public class Test {    public static void main(String[] args) {        LydApplicationContext applicationContext = new LydApplicationContext(AppConfig.class);        System.out.println(applicationContext.getBean("userService"));        System.out.println(applicationContext.getBean("userService"));        System.out.println(applicationContext.getBean("userService"));        System.out.println(applicationContext.getBean("userService"));        System.out.println(applicationContext.getBean("userService"));    }}我们可以先使用单例模式进行测试 , 我们不加scope注解,并且获取多个bean,可以看到得到的bean对象是同一个 。

【Spring系列】- 手写模拟Spring框架

文章插图
多例的时候在scope标上值,就可以看到每次获取的bean对象都是不一样的 。
【Spring系列】- 手写模拟Spring框架

文章插图
Autowired自动依赖注入当我们在UserService中使用RoleService,我们就需要通过Autowired注解进行依赖注入 。就是需要在createBean方法中,在创建实例之后,获取类中的字段,进行依赖注入,要通过判断Autowried注解 。通过字段的set方法,将bean对象注入 , 而这个对象如何获得呢?那就是用过getBean()方法 。
// 3 依赖注入for (Field field : clazz.getDeclaredFields()) {    // 判断字段上是否存在Autowried注解    if (field.isAnnotationPresent(Autowired.class)) {        /**         * 值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查 。         * 值为 false 则指示反射的对象应该实施 Java 语言访问检查;         * 实际上setAccessible是启用和禁用访问安全检查的开关,并不是为true就能访问为false就不能访问 ;         */        field.setAccessible(true); // 反射需要设置这个,不然无法赋值        // 用其属性名 , 这就意味着private RoleService roleService;roleService不能乱取        field.set(instance, getBean(field.getName()));    }}Aware回调机制与初始化Aware回调那如果我们需要获取当前bean的名字呢?那就得通过Aware回调机制 。我们需要创建一个BeanNameAware接口,里面提供一个setBeanName方法 。
public interface BeanNameAware {    public void setBeanName(String beanName);}在createBean方法中去编写回调机制,通过判断这个实例是否有BeanNameAware这个类,通过setName方法间接传递了beanName 。
// 4 Aware回调机制if (instance instanceof BeanNameAware) {    ((BeanNameAware)instance).setBeanName(beanName);}在UserService方法中去实现这个BeanNameAware方法,这就能够在UserService里的beanName字段中得到这个bean对象的真实的beanName了 。
@Component("userService") // 注入spring@Scope("property")public class UserService implements BeanNameAware, InitializingBean {    @Autowired    private RoleService roleService; // 依赖注入,加上@Autowired注解    private String beanName;    @Override    public void setBeanName(String beanName) {        this.beanName = beanName;    }    public void test() {        System.out.println("RoleService: " + roleService);    }    @Override    public void afterPropertiesSet() {        // ......        System.out.println("初始化");    }}

推荐阅读