【问题标题】:Create prototype scoped Spring bean with annotations?使用注释创建原型范围的 Spring bean?
【发布时间】:2012-04-12 21:12:34
【问题描述】:

是否可以将以下XML configuration 转换为基于注释的?

<bean id="myBean" class="my.package.MyBeanClass" scope="prototype" />

我正在使用 Spring 2.5.6

【问题讨论】:

    标签: java spring annotations scope javabeans


    【解决方案1】:

    你可以使用@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)注解。

    @Service
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public class CustomerService {
        // ...
    }
    
    1. Spring API Docs
    2. Example of the mapping
    3. Scope annotation reference.

    【讨论】:

    • 还有一个不错的常量可以用来代替字符串:BeanDefinition.SCOPE_PROTOTYPE
    • Scope注解Javadoc中,推荐的常量是ConfigurableBeanFactory.SCOPE_PROTOTYPE
    • 在 Spring 4 中删除了 BeanDefinition 类吗?
    • @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    • 或者使用@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)节省一点打字时间
    【解决方案2】:

    截至目前spring version 4.3.2,我们可以使用@Scope("prototype")注解。

    @Scope("prototype")
    @Repository
    public class MovieFinderImpl implements MovieFinder {
        // ...
    }
    

    【讨论】:

    • 我会说使用提供的常量,如接受的答案,更好。
    • @herman 是什么让它变得更好?是否有这方面的 JSR 标准?
    • @Steve 以防字符串更改(不太可能)或您想使用 IDE 搜索引用
    【解决方案3】:

    在 Spring 5 中,可以如下使用

    @Component("myBean")
    

    @Scope("prototype")

    public class MyBeanClass{//your logics}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多