[英]Spring config didn't work as expected
我正在建立一個新項目,並且我想嘗試一種新的方式來加載Spring配置。 我找到了@Configuration
批注,並決定嘗試一下。
@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");
如您所見,我以為可以從配置對象中獲取MyClass的春季配置實例,但是我必須從上下文對象中獲取它。
我想我誤解了@Configuration
和@Bean
工作方式。 我很近還是很遠?
您無法從cfg.getMyClass();
獲取bean cfg.getMyClass();
,有些誤會。
@Configuration
只是spring配置的另一種表示形式,您應該像application-context.xml
一樣理解它,這里沒有什么新鮮的。
這個
private static MyAppConfig cfg = new MyAppConfig();
不是Spring托管的bean,因此調用getMyClass()
時將為null
。
另外,以下
@ImportResource("classpath:myApp-config.xml")
同
@Autowired
private MyClass myClass;
@Bean(name="someOtherBeanName")
public MyClass getMyClass ()
{
return myClass;
}
是多余的。 由於@ImportResource
,因此XML配置中的bean已在上下文中。
指示一個或多個包含要導入的bean定義的資源。
您之間不需要其他的@Bean
方法。
您還有很長的路要走...以完整的基於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");
如果您仍然找不到config.xml或javaconfig.class,請添加您可能會遇到的東西。 檢查您的文件結構。
- src
- config.xml或javaconfig.java
要將配置保存在路徑中(默認軟件包為src)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.