2017-02-16 51 views
1

時,我有一個XML Bean文件彈簧自動裝配使用配置類

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
    <context:annotation-config/> 
    <bean id="helloWorld" class="com.a.b.HelloWorld"> 
     <property name="attr1" value="Attr1 from XML"></property> 
    </bean> 
    <bean id="helloWorld2" class="com.a.b.HelloWorld2"> 
     <property name="attr2" value="Attr2 from XML"></property> 
    </bean> 
</beans> 

而且我有使用自動裝配構造這樣

public class HelloWorld2{ 
     private String attr2; 
     public void setAttr2(String message){ 
      this.attr2 = message; 
     } 

     public void getAttr2(){ 
      System.out.println("getAttr2 == " + attr2); 
     } 


    } 

public class HelloWorld{ 
     private String attr1; 
     private HelloWorld2 helloWorld2;  
     public HelloWorld(){ 

     } 
     @Autowired 
     public HelloWorld(HelloWorld2 helloWorld2){ 
      System.out.println("hhh"); 
      this.helloWorld2 = helloWorld2; 
     } 


    public void setAttr1(String message){ 
      this.attr1 = message; 
     } 

     public void getAttr1(){ 
      System.out.println("getAttr1 == " + attr1); 
     } 
     public void getH(){ 
      helloWorld2.getAttr2(); 
     } 
    } 

而且自動連接工作正常。

現在我想將我的豆移動到配置類。 但隨後如何移動代碼,使自動裝配工程?

我已經試過這樣的,但它不工作

@Configuration 
public class Config { 
    @Bean 
    public HelloWorld helloWorld(){ 
     HelloWorld a = new HelloWorld(); 
     a.setAttr1("Demo Attr1"); 
     return a; 

    } 

    @Bean 
    public HelloWorld2 helloWorld2(){ 
     HelloWorld2 a = new HelloWorld2(); 
     a.setAttr2("Demo Attr2"); 
     return a;    
    } 
} 
+1

[轉換春天XML文件的可能的複製Spring @Configuration類](http://stackoverflow.com/questions/2 4014919/convert-spring-xml-file-to-spring-configuration-class) – James

回答

3

我想你想達到什麼是注射HelloWorld2實例爲創建該HelloWorld@Bean的方法?

這應做到:

@Configuration 
public class Config { 
    @Bean 
    public HelloWorld helloWorld(HelloWorld2 helloWorld2){ 
     HelloWorld a = new HelloWorld(helloWorld2); 
     a.setAttr1("Demo Attr1"); 
     return a; 

    } 

    @Bean 
    public HelloWorld2 helloWorld2(){ 
     HelloWorld2 a = new HelloWorld2(); 
     a.setAttr2("Demo Attr2"); 
     return a;    
    } 
} 

這可能是這些問題的一個重複:

+0

它可以稍作修改。我還必須更改 HelloWorld a = new HelloWorld(); 到HelloWorld a = new HelloWorld(helloWorld2); 這是正確的方法嗎? –

+0

是的,很好的地方。 – James

+0

但是現在,即使當我從HelloWorld構造函數中刪除了@Autowired並且obj1.getH()的O/p給了我Demo Demo Attr2時,此代碼仍在工作。它是如何發生的?我的意思是HelloWorld如何在沒有自動裝配的情況下獲取HelloWorld2的實例? –