2013-10-04 43 views
0

我正在構建一個新項目,我想我會嘗試一種加載我的Spring配置的新方法。我找到@Configuration註釋,並決定試一試。Spring配置沒有按預期工作

@Configuration 
@ImportResource("classpath:myApp-config.xml") 
public class MyAppConfig 
{ 
    @Autowired 
    private MyClass myClass; 

    @Bean(name="someOtherBeanName") 
    public MyClass getMyClass() 
    { 
     return myClass; 
    } 

    public void setMyClass(myClass m) 
    { 
     this.myClass= m; 
    } 
} 

在Spring配置文件:

<context:annotation-config/> 
<bean name="someOtherBeanName" class="com.MyClass"> 
    <property name="myClass"> 
     <map> 
      <!-- details not relevant --> 
     </map> 
    </property> 
</bean> 

要利用這一點,我有這樣的代碼:

//class member 
private static MyAppConfig cfg = new MyAppConfig(); 
... 
... 
... 
//In the class that needs the configuration 
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
ctx.register(MyAppConfig.class); 
ctx.refresh(); 
//appMgr = cfg.getMyClass(); 
appMgr = (MyClass) ctx.getBean("someOtherBeanName"); 

正如你所看到的,我以爲我可以從我的配置對象中獲取一個Spring配置的MyClass實例,但是我必須從我的上下文對象中獲取它。

我想我誤解了@Configuration@Bean的工作方式。我相當接近還是離開?

回答

1

你不能從cfg.getMyClass();得到你的豆,有一些誤解。

@Configuration只是彈簧配置的另一種表示方式,您應該瞭解它,就像您的application-context.xml一樣,這裏沒有什麼新東西。

+0

取決於你的意思。如果OP從'ctx'獲得'cfg'對象,那麼是的,他們可以使用'cfg.getMyClass()'來獲取bean。 –

+0

你是對的,我誤解了如何使用'@ Configuration' - 我想我可以使用它作爲加載我的配置的一種更簡單的方式,而不是它* *我的配置。 – FrustratedWithFormsDesigner

0

private static MyAppConfig cfg = new MyAppConfig(); 

不是Spring管理豆所以調用getMyClass()時,你會得到null

而且,下面的

@ImportResource("classpath:myApp-config.xml") 

@Autowired 
private MyClass myClass; 

@Bean(name="someOtherBeanName") 
public MyClass getMyClass() 
{ 
    return myClass; 
} 

是多餘的。由於@ImportResource,來自XML配置的bean已經在上下文中。

指示一個或多個包含要導入的bean定義的資源。

您不需要額外的@Bean方法。

0

你很遙遠......要全面的基於Java的配置將是你的榜樣:

@Configuration 
public class MyAppConfig { 

    @Bean 
    public MyClass someOtherBeanName() { 
     MyClass myClass = new MyClass(); 
     myClass.setMyProp(null /* details not relevant */); 
     return myClass; 
    } 

} 

別的地方在main方法(這是不變):

//In the class that needs the configuration 
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
ctx.register(MyAppConfig.class); 
ctx.refresh(); 
//appMgr = cfg.getMyClass(); 
appMgr = (MyClass) ctx.getBean("someOtherBeanName"); 
0

添加你可能會遇到的東西,如果你仍然無法找到config.xml或javaconfig.class。檢查你的文件結構。

  • SRC
    • config.xml中javaconfig.java

要保存你的配置在你的路徑(默認包爲src )