💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> JSR 330’s @Inject可以替代 @Autowired在下面的示例中, > 可以应用在构造方法上 ~~~ public class MovieRecommender { private final CustomerPreferenceDao customerPreferenceDao; @Autowired public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) { this.customerPreferenceDao = customerPreferenceDao; } // ... } ~~~ 也可以应用在传统的set方法上 ~~~ public class SimpleMovieLister { private MovieFinder movieFinder; @Autowired public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // ... } ~~~ 也可以应用在任意参数的方法上 ~~~ public class MovieRecommender { private MovieCatalog movieCatalog; private CustomerPreferenceDao customerPreferenceDao; @Autowired public void prepare(MovieCatalog movieCatalog, CustomerPreferenceDao customerPreferenceDao) { this.movieCatalog = movieCatalog; this.customerPreferenceDao = customerPreferenceDao; } // ... } ~~~ 也可以混合使用 ~~~ public class MovieRecommender { private final CustomerPreferenceDao customerPreferenceDao; @Autowired private MovieCatalog movieCatalog; @Autowired public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) { this.customerPreferenceDao = customerPreferenceDao; } // ... } ~~~ 也可以用在数组上 ~~~ public class MovieRecommender { @Autowired private MovieCatalog[] movieCatalogs; // ... } ~~~ 也可以用在集合上 ~~~ public class MovieRecommender { private Set<MovieCatalog> movieCatalogs; @Autowired public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) { this.movieCatalogs = movieCatalogs; } // ... } ~~~ >如果要对集合排序,可以让bean实现`org.springframework.core.Ordered`接口,或使用`@Order` 和`@Priority`注解. 也可以用在map上,key是string类型,代表bean的name,value是bean的实例 ~~~ public class MovieRecommender { private Map<String, MovieCatalog> movieCatalogs; @Autowired public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) { this.movieCatalogs = movieCatalogs; } // ... } ~~~ 默认,@Autowired是必需的,如果没有可绑定的类型,则失败,这种行为可以被改变,如下: ~~~ public class SimpleMovieLister { private MovieFinder movieFinder; @Autowired(required = false) public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // ... } ~~~ 或者,您可以通过Java 8的java.util.Optional表达特定依赖项的非必需性质: ~~~ public class SimpleMovieLister { @Autowired public void setMovieFinder(Optional<MovieFinder> movieFinder) { ... } } ~~~ 对于spring5,可以使用`@Nullable(javax.annotation.Nullable)`注解 ~~~ public class SimpleMovieLister { @Autowired public void setMovieFinder(@Nullable MovieFinder movieFinder) { ... } } ~~~ 也可以用在解决依赖的`BeanFactory, ApplicationContext, Environment, ResourceLoader, ApplicationEventPublisher, and MessageSource`,还有继承的接口`ConfigurableApplicationContext or ResourcePatternResolver` ~~~ public class MovieRecommender { @Autowired private ApplicationContext context; public MovieRecommender() { } // ... } ~~~