SpringBoot三种Bean注入方式


4个月前 191次点击 来自 后端

标签: SpringBoot

1. 基于字段的依赖注入

public class UserServiceImpl implents UserService{
     @Autowire
     private UserDao userDao;
 }

2. 基于构造函数的依赖注入

public class UserServiceImpl implents UserService{
     private UserDao userDao;
     
     @Autowire
     public serUserDao(UserDao userDao){
         this.userDao = userDao;
     }
 }

3. 基于Setter的依赖注入

public class UserServiceImpl implents UserService{
    private UserDao userDao;
    
    @Autowire
    public UserServiceImpl(UserDao userDao){
        this.userDao = userDao;
    }
}

官方推荐使用 2,3 ,使用第一种方式会warning:

Field injection is not recommended Inspection info: Spring Team recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1

Top ↑