Blog Home
Updated: 2023 Oct 09

字段注入,构造函数注入,setter注入

class FooService {
  @Autowired
  private BarDao barDao;
  
  @Autowired
  private BazDao bazDao;
  
  ...
}

class FooService {
  private final BarDao barDao;
  private final BazDao bazDao;
  
  @Autowired
  public FooService(BarDao barDao, BazDao bazDao) { 
      this.barDao = barDao;
      this.bazDao = bazDao;
  }
  
  ...
}

class FooService {                                                                                                    
  private BarDao barDao;                                                                                              
  private BazDao bazDao;                                                                                              
                                                                                                                     
  public BarDao getBarDao() {
  	return barDao;
  }
  
  @Autowired
  public void setBarDao(BarDao barDao) {
  	this.barDao = barDao;
  }    
  
  public BarDao getBazDao() {
  	return bazDao;
  }
  
  @Autowired
  public void setBazDao(BazDao bazDao) {
  	this.bazDao = bazDao;
  }

  ...                                                                                                     
}

推荐使用构造函数注入方式。 link: https://www.petrikainulainen.net/software-development/design/why-i-changed-my-mind-about-field-injection/

Comments:

Email questions, comments, and corrections to hi@smartisan.dev.

Submissions may appear publicly on this website, unless requested otherwise in your email.