💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
Spring从3.0开始提供 JSR-330标准的注释。(依赖注入) 需要添加 <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> 1.11.1 使用 @Inject 和@Named 配置依赖注入 替换@Autowired, @javax.inject.Inject 用法如下: import javax.inject.Inject; public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } public void listMovies() { this.movieFinder.findMovies(...); ... } } } 和@Autowired一样, 也可以在字段层级、方法层级和构造参数层级使用@Inject, 使用@Name 指定Bean import javax.inject.Inject; import javax.inject.Named; public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(@Named("main") MovieFinder movieFinder) { this.movieFinder = movieFinder; } // ... } }  和@Autowired一样, @Inject同样可以使用java.util.Optional和 @Nullable。 1.11.2 @Named and @ManagedBean 与 @Component注释等效 import javax.inject.Inject; import javax.inject.Named; @Named("movieListener") // @ManagedBean("movieListener") could be used as well public class SimpleMovieLister { private MovieFinder movieFinder; @Inject public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // ... } } 1.11.3 JSR-330标准注释的局限 Spring javax.inject.* javax.inject restrictions / comments @Autowired @Inject @Inject has no 'required' attribute; can be used with Java 8’s Optionalinstead. @Component @Named / @ManagedBean JSR-330 does not provide a composable model, just a way to identify named components. @Scope("singleton") @Singleton The JSR-330 default scope is like Spring’s prototype. However, in order to keep it consistent with Spring’s general defaults, a JSR-330 bean declared in the Spring container is a singleton by default. In order to use a scope other than singleton, you should use Spring’s @Scopeannotation. javax.inject also provides a @Scope annotation. Nevertheless, this one is only intended to be used for creating your own annotations. @Qualifier @Qualifier / @Named javax.inject.Qualifier is just a meta-annotation for building custom qualifiers. Concrete String qualifiers (like Spring’s @Qualifier with a value) can be associated through javax.inject.Named. @Value - no equivalent @Required - no equivalent @Lazy - no equivalent ObjectFactory Provider javax.inject.Provider is a direct alternative to Spring’s ObjectFactory, just with a shorter get() method name. It can also be used in combination with Spring’s @Autowired or with non-annotated constructors and setter methods