我通过 Google Guice 进入 IOC。
现在我被迫在工作中使用 Spring 2.5.6 & 我迷失了,因为 Spring 非常复杂。在阅读了 Spring 文档的一些内容后,这里有一些问题:
@Service
、@Controller
和@Component
之间有什么区别?如果我只是想像 Guice 一样自动连接我的对象,我是否需要被所有这些刻板印象所困扰?我计划采用组件扫描路线,仅使用构造函数注入(inject)(Setter 注入(inject)主要由山达基教会提倡),而不使用任何奇怪的 XML 内容。那么这段代码提取就是我所需要的吗?
@Component public class Foo { @Autowired(required=true) public Foo( Bar bar, @Qualifier("yay") Boo yay, @Qualifier("hoo") Boo hoo ) { _bar = bar; _boo = boo; } Bar _bar; Boo _boo; ....snipped... } @Component @Qualifier("yay") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public BooYay implements Boo { } @Component @Qualifier("hoo") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public BooHoo implements Boo { }
- 在上面的示例中,我是否正确限定了
Boo
的 2 个不同实现? - 是否有与 Google Guice 的 Providers 类似的功能?
- 如何在 Spring 中模仿
@Singleton
行为(在 Guice 中)?
- 在上面的示例中,我是否正确限定了
最佳答案
看看你的代码,看起来一切都很好,你的组件将得到 Autowiring
。您必须在 XML 配置文件中提供包名称,以便 Spring 可以扫描其中的注释。
一般来说,Spring 管理的组件,自动检测组件的默认且最常见的范围是单例。
实际上,@Component是@Service和@Controller的泛化。请参阅docs .
Spring 2.5 introduces further stereotype annotations: @Component, @Service and @Controller. @Component serves as a generic stereotype for any Spring-managed component; whereas, @Repository, @Service, and @Controller serve as specializations of @Component for more specific use cases (e.g., in the persistence, service, and presentation layers, respectively). What this means is that you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. Of course, it is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are making a decision between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is already supported as a marker for automatic exception translation in your persistence layer.
确保这些 Bean 的 default-autowire
或 autowire
值为 byType
。然后你应该像下面这样修改你的 Boo 组件,
@Component("yay")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public BooYay implements Boo
{...}
@Component("hoo")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public BooHoo implements Boo
{...}
您可能希望使用 autowire = "byName"
来完成此操作,在这种情况下,您将不需要 @Qualifiers
,但必须提供匹配的 setter 。我希望你现在能成功完成这件事。
关于java - Spring 的带注释的 IOC 对于 Guice 人来说是令人困惑的。帮助启发我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1753296/