IT袋

当前位置:主页 > 对比评测 >

@Configuration和@Component区别

@Configuration和@Component区别(2)

时间:2024-01-19 13:40:55 来源:IT袋 作者:马勇
导读:@Configuration和@Component区别,Spring 对于配置类来讲,其实是有分类的,大体可以分为两类 : FULL模式 : Full 模式最大的特点是会给配置类通过 CGLIB 生成一个代理,Configuration就是FULL类型

@Configuration和@Component区别

Spring对于配置类来讲,其实是有分类的,大体可以分为两类:

  • FULL模式: Full 模式最大的特点是会给配置类通过 CGLIB 生成一个代理,Configuration就是FULL类型
  • LITE模式: Lite 模式,这种模式可以认为是一种精简模式,@Component就是Lite类型

2.1 FULL模式

FULL模式: Full 模式最大的特点是会给配置类通过 CGLIB 生成一个代理,Configuration就是FULL类型

思考:为什么要代理呢?

我们从下面一个案例进行分析:

@Configuration
public class MyConfig01 {
    @Bean
    Dog dog(){
        return new Dog();
    }
    @Bean
    Person person(){
        Person person = new Person();
        //注意,这里是将上面注册到Spring中的dog,set到person
        person.setDog(dog());
        return person;
    }
}

测试:

@Test
  public void test1() {
      AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DiffApplication.class);
      Person person = ctx.getBean("person", Person.class);
      Dog dog = ctx.getBean("dog", Dog.class);
      boolean result = person.getDog() == dog;
      System.out.println(result ? "同一个dog" : "不同的dog");
  }

结果

同一个dog

原因分析:Full 模式下,person() 方法中调用 dog() 方法的时候,调用的是一个代理对象中的 dog 方法,在这个代理对象的 dog 方法中,先去检查 Spring 容器中是否存在 Dog 对象,如果存在,则直接使用 Spring 容器中的 dog 对象,就不会真正去执行 dog 方法而获取到一个新的 dog 对象了,如果 Spring 容器中不存在 dog 对象,才会创建新的 dog 对象出来

总结;在 Full 模式下,person 中的 dog 对象和 dog 方法注册到 Spring 容器的 dog 对象是同一个。

注意:Full 模式下@Bean 注解标记的方法不能是 final 或者 private 类型,,因为 final 或者 private 类型的方法无法被重写,也就没法生成代理对象

特别说明:@Configuration注解如果设置了 proxyBeanMethods 属性为 false,就是 Lite 模式了

2.2. LITE模式

LITE模式: Lite 模式,这种模式可以认为是一种精简模式,@Component就是Lite类型

将MyConfig01配置类上的注解变为@Component:

@Component
public class MyConfig01 {
    @Bean
    Dog dog(){
        return new Dog();
    }
    @Bean
    Person person(){
        Person person = new Person();
        //注意,这里是将上面注册到Spring中的dog,set到person
        person.setDog(dog());
        return person;
    }
}

大家猜一下结果如何?

不同的dog

总结:LITE模式下Spring 容器中拿到的就是原始的对象,而不是一个被代理过的对象

以上就是IT袋网带来的@Configuration和@Component区别的具体介绍,希望大家能喜欢!

相关阅读