Spring的依赖注入,我们一般使用@Autowired注解来完成,关于依赖注入一般有三种方式:
变量注入、构造器注入、setter方法注入,下面我们仔细分析一下三种注入方式各自的特点以及使用场景。
先看看怎么使用:
@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; //... }
使用IDEA开发的时候,我们发现直接在变量上注解 @Autowired,它会有个警告提示:Field injection is not recommended。如下图:
具体是: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"。
意思是说“变量依赖注入是不被建议的方式”。Spring官方建议“总是采用构造器注入的方式建立依赖注入”。
优点:
弊端:
先看看怎么使用:
@Service public class UserServiceImpl implements UserService { private final UserMapper userMapper; @Autowired public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; } }
优点:
弊端:
使用 IEDA 可以在修改变量后重新使用快捷键生成构造方法。
先看看怎么使用:
@Service public class UserServiceImpl implements UserService { private UserMapper userMapper; @Autowired public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } }
优点:
弊端: