Spring Bean的创建过程

Spring Bean的创建过程

以下代码是学习Spring的hello world,第一行代码中的ApplicationContext会管理项目中的bean,本文从Bean的创建过程展开...

    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
    UserService userService = applicationContext.getBean(UserService.class);

bean的生成过程如下:

推断构造方法 -> 普通对象 -> 依赖注入(DI)-> 初始化前(@PostConstruct)->  初始化(implements InitializingBean) -> 初始化后(AOP)-> Bean


推断构造方法

先扫描指定目录下带@Component的class, 然后通过推断构造方法来先生成一个实例

  • 如果该类只有一个构造方法就用该构造方法来生成对象
    example(只有一个无参构造)

    @Component
    public class UserService {
    
        public static final Logger logger = LoggerFactory.getLogger(UserService.class);
    
        @Autowired
        private OrderService orderService;
    
        public UserService() {
            logger.info("UserService construct -- without param ");
        }
    
        public String getUerNameById(int userId) {
            return "simon";
        }
    }
    

    测试类

    public class ApplicationTests {
        public static final Logger logger = LoggerFactory.getLogger(ApplicationTests.class);
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
            UserService userService = applicationContext.getBean(UserService.class);
            String uerName = userService.getUerNameById(1);
            logger.info(uerName);
        }
    }
    
    

    从运行结果可知使用无参构造来初始化bean

    example(只有一个有参构造)

    @Component
    public class UserService {
    
        public static final Logger logger = LoggerFactory.getLogger(UserService.class);
    
        @Autowired
        private OrderService orderService;
    
        public UserService() {
            logger.info("UserService construct -- without param ");
        }
    
        public String getUerNameById(int userId) {
            return "simon";
        }
    }
    

    从运行结果可知使用有参构造来初始化bean


  • 如果该类有多个构造方法,使用无参构造方法,没有无参就报错

    example(一个无参构造,一个有参)

        public UserService() {
            logger.info("UserService construct -- without param ");
        }
    
        public UserService(OrderService orderService) {
            logger.info("UserService construct -- with orderService");
        }
    

    从运行结果可知使用仍无参构造来初始化的bean

    example(两个有参,没有无参)

      public UserService() {
          logger.info("UserService construct -- without param ");
      }
    
      public UserService(OrderService orderService) {
          logger.info("UserService construct -- with orderService");
      }
    

    找不到默认的构造方法,exception:No default constructor found

依赖注入

通过构推断法得到一个实例后,Spring会判断该对象中的属性是否含有@Autowired, 如果有的话就把这些属性从context中找出来,然后注入到该对象中

初始化前

初始化

初始化后(AOP)得到新的代理对象

posted @ 2022-02-12 22:17  LALALA823  阅读(871)  评论(0编辑  收藏  举报