我正在构建一个新项目,我想我会尝试一种新的方式来加载我的 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;
}
}
在弹簧配置文件中:
<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
工作。我离得很近还是很远?