我在挥杆/弹簧应用中有各种挥杆动作。它们注释为@Component,因此它们应在组件自动扫描后可见。我有一个配置类,我正在为主框架/窗口的菜单定义一个bean。创建/返回菜单对象的方法必须根据需要引用操作。在Beans.xml设置中,我只会执行以下操作:
<bean id="mainMenu" class="javax.swing.JMenu">
<constructor-arg id="0" value="Schedule" />
<constructor-arg id="1">
<value type="int">0</value>
</constructor>
</bean>
然后,在主窗体中bean的setter中,我会在setter之前自动装配并添加项目。在摆动中,没有办法将属性设置为菜单项 - 您必须添加它们。在beans.xml设置中,我可以通过id或在另一个bean的创建中输入bean来引用bean。我如何在配置类中执行此操作?像这是我的配置类:
@Configuration
@ComponentScan("net.draconia.ngucc.usher")
public class BeanConfiguration
{
private Action mActCreateSchedule, mActEditSchedule, mActExit, mActRemoveSchedule;
private JMenu mMnuSchedule;
@Bean("scheduleMenu")
public JMenu getScheduleMenu()
{
if(mMnuSchedule == null)
{
mMnuSchedule = new JMenu("Schedule");
mMnuSchedule.setMnemonic(KeyEvent.VK_S);
mMnuSchedule.add(getCreateScheduleAction());
mMnuSchedule.add(getEditScheduleAction());
mMnuSchedule.add(getRemoveScheduleAction());
mMnuSchedule.addSeparator();
mMnuSchedule.add(getExitAction());
}
}
}
我希望能够代替get函数,或者可能有get函数来访问项目 - 在get函数中会出现类似return((CreateSchedule)(getBean(CreateSchedule.class)))(我想我有足够/正确数量的括号哈哈)。我只需要访问应用程序上下文。我可以以某种方式在配置类中自动装配一个(应用程序上下文),或者我如何可以访问getBean来访问这些组件扫描的bean?
提前谢谢!
答案 0 :(得分:0)
@Autowired
ApplicationContext到配置类
@Configuration
@ComponentScan("net.draconia.ngucc.usher")
public class BeanConfiguration
{
private Action mActCreateSchedule, mActEditSchedule, mActExit, mActRemoveSchedule;
private JMenu mMnuSchedule;
@Autowired
ApplicationContext context;
@Bean("scheduleMenu")
public JMenu getScheduleMenu()
{
if(mMnuSchedule == null)
{
mMnuSchedule = new JMenu("Schedule");
mMnuSchedule.setMnemonic(KeyEvent.VK_S);
mMnuSchedule.add(getCreateScheduleAction());
mMnuSchedule.add(getEditScheduleAction());
mMnuSchedule.add(getRemoveScheduleAction());
mMnuSchedule.addSeparator();
mMnuSchedule.add(getExitAction());
}
}
}
另一种解决方案是使用ApplicationContextAware接口,如:
@Component
public class ContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
ContextUtil.context=context;
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
ContextUtil.context = context;
}
public static Object getBean(String beanName){
return getContext().getBean(beanName);
}
}