2017-08-13 101 views
0

我在摆动/弹簧应用程序中有各种摆动动作。它们被注释为@Component,所以它们应该在组件自动扫描后可见。我有一个配置类,我为主框架/窗口的菜单定义了一个bean。创建/返回菜单对象的方法必须根据需要引用操作。在beans.xml的设置,我只想做这样的事情:春天我如何在配置类中引用其他bean?

<bean id="mainMenu" class="javax.swing.JMenu"> 
    <constructor-arg id="0" value="Schedule" /> 
    <constructor-arg id="1"> 
      <value type="int">0</value> 
    </constructor> 
</bean> 

然后,在二传手为主要形式的豆,我会setter方法之前自动装配,并添加项目。在摆动中,没有办法将属性设置为菜单项 - 您必须添加它们。在beans.xml设置中,我可以通过id引用一个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函数,则有可能会像回报((CreateSchedule )(getBean(CreateSchedule.class)))(我想我有足够的/正确数量的括号哈哈)。我只需要访问应用程序上下文。我可以以某种方式在配置类中自动调用一个(应用程序上下文),或者我可能如何访问getBean来访问这些组件扫描的bean?

预先感谢您!

回答

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); 
    } 

} 
+0

我给这些建议一杆 - 谢谢你! –