2017-08-13 105 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

我給這些建議一杆 - 謝謝你! –