2017-02-22 1 views
2

In XML Kontext basiert Bean-Konfigurationsdatei auf eine andere Bean verweisen, wenn ich eine Bohne als Eigentum beziehen möchten, würde ich verwenden:Wie als Eigenschaft in Annotation-basierte Konfigurationsdatei

<bean class="com.example.Example" id="someId"> 
    <property name="someProp" refer="anotherBean"/> 
</bean> 
<bean class="com.example.AnotherBean" id="anotherBean"> 
</bean> 

So ist die Example Bohne die anotherBean als sein Eigentum

so in dem Konzept der Annotation-basierte Konfiguration Java-Datei:

@Configuration 
class GlobalConfiguration { 
    @Bean 
    public Example createExample(){ 
     return; 
     //here how should I refer to the bean below? 
    } 

    @Bean 
    public AnotherBean createAnotherBean(){ 
     return new AnotherBean(); 
    } 
} 

Antwort

6

Hier eine erste Lösung ist, wh Sie haben beide Bean Definitionen in einer Klasse.

@Configuration 
class GlobalConfiguration { 
    @Bean 
    public Example createExample(){ 
     final Example example = new Example(); 
     example.setSomeProp(createAnotherBean()); 
     return example; 
    } 

    @Bean 
    public AnotherBean createAnotherBean(){ 
     return new AnotherBean(); 
    } 
} 

zweite Möglichkeit ist, wie unten zu verwenden autowiring:

@Configuration 
    class GlobalConfiguration { 
     @Bean 
     @Autowired 
     public Example createExample(AnotherBean anotherBean){ 
      final Example example = new Example(); 
      example.setSomeProp(anotherBean); 
      return example; 
     } 

     @Bean 
     public AnotherBean createAnotherBean(){ 
      return new AnotherBean(); 
     } 
    } 

dritte Möglichkeit besteht darin, diese Erklärungen unter zwei verschiedenen @Configuration Klassen und autowiring verwenden aufzuspalten.

@Configuration 
class FirstConfiguration { 

    @Bean 
    public AnotherBean createAnotherBean(){ 
     return new AnotherBean(); 
    } 
} 

@Configuration 
class SecondConfiguration { 

    @Autowired 
    private AnotherBean anotherBean; 

    @Bean 
    public Example createExample(){ 
     final Example example = new Example(); 
     example.setSomeProp(anotherBean); 
     return example; 
    } 
} 
+0

Sie könnten auch die '@ Autowired'annotation (mit vielleicht ein' @ Qualifier') in der Beispiel-Bean-Klassendefinition hinzufügen, wenn das möglich ist und die Setter in der Bohne Instanziierung überspringen. –

+1

danke @ JeremyGrand, Ich habe nur die zweite Lösung überprüft, die Sie vorgeschlagen haben, da es ordentlich und gut aussieht. Es funktioniert, die zweite Lösung, danke. – cinqS

Verwandte Themen