gpt4 book ai didi

java - 带有注解的 Spring IOC 会让 Guice 人感到困惑。帮忙开导一下

转载 作者:行者123 更新时间:2023-11-30 07:38:29 31 4
gpt4 key购买 nike

我是通过 Google Guice 进入国际奥委会的。

现在我不得不在工作中使用 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-autowireautowire 值为 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com