Reference document: https: //www.cnblogs.com/wang-yaz/p/9340156.html
reference documentation: http: //www.pianshen.com/article/5023380349/
First, we need to understand that use three @Autowired injection the way:
@Service("accountEmailService")
2 public class AccountEmailServiceImpl implements AccountEmailService{
3
4
5 /** 通过构造器注入---begin **/
6 private JavaMailSender javaMailSender;
7
8 @Autowired
9 public AccountEmailServiceImpl(JavaMailSender javaMailSender){
10 this.javaMailSender = javaMailSender;
11 }
12
13
14 /** 通过set方法注入---begin **/
15 private JavaMailSender javaMailSender;
16 @Autowired
17 public void setJavaMailSender(JavaMailSender javaMailSender){
18 this.javaMailSender = javaMailSender;
19 }
20
21
22 /** 通过field注入 **/
23 @Autowired
24 private JavaMailSender javaMailSender;
25
Spring is recommended to use constructor injection:
Spring Team Recommends: "Always use constructor based dependency Injection in your Beans Always use Assertions mandatory for the Dependencies.."
Because there may be injected into the field NullPointerException
class MyComponent {
@Inject MyCollaborator collaborator;
public void myBusinessMethod() {
collaborator.doSomething(); // -> NullPointerException
}
}
However constructor injection because the code is simple enough that we do not only abandoned the. And in fact, we have been using have not made a mistake with property injection. So there are two solutions:
first: the "@Autowired" Notes changed to "@Resouce" comment.
@Resource is JSR-250 specification annotations, Spring currently has supported the specification. @Resource is the first to match the name according to Bean of Bean, get less, then again to match the type; and @Autowired is based on the type of match, you need to by name Spring of @Qualifier annotations work with.
The second: Modify setting field of injection inside inspection: setting-> editor-> code style-> inspection-> spring-> spring core-> code, remove the hook: