在这篇文章中,我们将讨论一个非常重要的Spring依赖注入注解,即@Autowired
注解。
我们可以使用@Autowired
来标记Spring将要解析和注入的依赖关系。我们可以在构造器、设置器或域注入中使用这个注解。
下图显示了@Autowired
注解的内部实现。
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
}
@Autowired
注解可以应用于不同的层次或场景。下面是一些相同的例子。
**例子:**将注解应用于具有任意名称和/或多个参数的方法。
public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
**示例:**将@Autowired
也应用于字段,甚至与构造函数混合。
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
private MovieCatalog movieCatalog;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
**示例:**将@Autowired
注解应用于期望有该类型数组的字段或方法。
public class MovieRecommender {
@Autowired
private MovieCatalog[] movieCatalogs;
// ...
}
**示例:**将@Autowired
注解应用于同样适用于类型的集合。
public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
@Autowired
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
你可以通过Java 8的java.util.Optional来表达特定依赖的非必需性质。
public class SimpleMovieLister {
@Autowired
public void setMovieFinder(Optional<MovieFinder> movieFinder) {
...
}
}
对于众所周知的可解析依赖的接口,我们也可以使用@Autowired
:BeanFactory, ApplicationContext, Environment, ResourceLoader, ApplicationEventPublisher, and MessageSource
。
public class MovieRecommender {
@Autowired
private ApplicationContext context;
public MovieRecommender() {
}
// ...
}
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired(required = false)
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/09/spring-autowired-annotation-with-example.html
内容来源于网络,如有侵权,请联系作者删除!