【问题标题】:Java Spring Annotation equivalent of referenceJava Spring Annotation 等价于参考
【发布时间】:2017-06-12 17:28:02
【问题描述】:

我正在尝试从 XML 配置中移出,但对等效于什么感到困惑 <spring:property name="beanName" ref="beanToReference">

我认为它会类似于 @Value("${Property.Value}") 注释

任何帮助将不胜感激!

【问题讨论】:

    标签: java spring annotations


    【解决方案1】:

    你可以这样引用它:

    @Bean
    MyAnotherBean myAnotherBean() {
        return new MyAnotherBean();
    }
    
    @Bean
    MyBean myBean(MyAnotherBean beanToReference) {
        final MyBean myBean = new MyBean();
        myBean.setAnotherBean(beanToReference);
        return myBean;
    }
    

    或者像这样(如果两个 bean 在同一个配置类中):

    @Bean
    MyAnotherBean myAnotherBean() {
        return new MyAnotherBean();
    }
    
    @Bean
    MyBean myBean() {
        final MyBean myBean = new MyBean();
        myBean.setAnotherBean(myAnotherBean());
        return myBean;
    }
    

    【讨论】:

      【解决方案2】:

      假设你有两个这样的 bean

      @Compenent
      public class SampleBeanOne{
      }
      
      @Compenent
      public class SampleBeanTwo{
      }
      

      并且您想像在主组件的 xml 文件中定义的那样使用它们

      @Compenent
      public class MainComponent{
      
          @Autowired
          private SampleBeanOne sampleBeanOne;         
      
          @Autowired
          private SampleBeanTwo sampleBeanTwo;         
      
      }
      

      首先你应该像这样启用@Autowired注解

      <beans  
          xmlns:context="http://www.springframework.org/schema/context"
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-2.5.xsd">
      
          <context:annotation-config />
      </beans>
      

      启用注解注入后,可以在属性、设置器和构造器上使用自动装配。

      默认情况下,Spring 按类型使用@Autowired。如果您有多个相同类型的 bean,框架将抛出​​一个异常,表明有多个 bean 可用于自动装配。为了解决这个问题,您可以使用 @Qualifier 注释。

      Spring 使用 bean 名称作为默认限定符值,所以如果你像这样使用它:

          @Autowired
          private SampleBeanOne myBean;
      

      它假定您有 SampleBeanOne 的 MyBean 实现,并尝试对其进行微调并将其注入到您的组件构造中。

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 2012-06-22
        • 2018-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-25
        • 2013-11-24
        • 2010-11-23
        相关资源
        最近更新 更多