我正在構建一個新項目,我想我會嘗試一種加載我的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
的工作方式。我相當接近還是離開?
取決於你的意思。如果OP從'ctx'獲得'cfg'對象,那麼是的,他們可以使用'cfg.getMyClass()'來獲取bean。 –
你是對的,我誤解了如何使用'@ Configuration' - 我想我可以使用它作爲加載我的配置的一種更簡單的方式,而不是它* *我的配置。 – FrustratedWithFormsDesigner