当前位置:网站首页>@The difference between Autowired and @resource

@The difference between Autowired and @resource

2022-07-06 12:17:00 A pole

@Autowired and @Resource The difference between

Different default injection methods

@Autowired The default injection method is byType( Match by type ), In other words, it will give priority to matching and injecting according to the interface type Bean ( Implementation class of interface ), If you want to specify a name , Can pass @Qualifier In combination with .

@Autowired
private UserSafetyMapper userSafetyMapper;

//  or 
@Autowired @Qualifier("userSafetyMapper")
private UserSafetyMapper userSafetyMapper;

@Resource The default injection method is byName( Match according to the name ). If you cannot match the corresponding implementation class by name , The injection method will change to byType.

  1. If you also specify name and type, From Spring Unique match found in context bean Assembly , Throw exception if not found ;
  2. If you specify name, Find name from context (id) Matching bean Assembly , Throw exception if not found ;
  3. If you specify type, Then find the unique type match from the context bean Assembly , Can't find or find more than one , Will throw an exception ;
  4. If neither name, It's not specified type, Then automatically follow the byName Method of assembly ; If there is no match , Back off to match as an original type , Auto assemble if match .
// 1. Default injection mode 
@Resource
private UserSafetyMapper userSafetyMapper;

// 2. Specify the injection method 
@Resource(name = "userSafetyMapper", type = UserSafetyMapper.class)
private UserSafetyMapper userSafetyMapper;

Different providers

@Autowired yes spring Notes provided ,@Resource yes JDK Notes provided

原网站

版权声明
本文为[A pole]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060913401082.html