2012-08-17 95 views
1

在我們的獨立Spring 3.1應用程序中,我們嚴格地將業務邏輯從監視Swing視圖中分離出來。該視圖通過實現EventListener接口來獲得其信息。如何在運行或啓動時在Spring中禁用服務?

要禁用UI,只需「移除」UI Bean上的所有@Services即可,以便實現此EventListner的UI類不會被業務邏輯注入。

但如何做到這一點?

這個例子給我們的類的小Oerview:

@Service 
public class UI extends JFrame implements EventListener { 
    @PostConstruct 
    public void setup() { 
     // Do all the Swing stuff 
     setVisible(true); 
    } 

    @Override 
    public void onBusinessLogicUpdate(final State state) { 
     // Show the state on the ui 
    } 
} 

@Service 
public class Businesslogic { 
    @Autowired 
    public List<EventListener> eventListeners; 

    public void startCalculation() { 

     do { 
      // calculate ... 
      for (final EventListener listener : this.eventListeners) { 
       eventlistener.onBusinessLogicUpdate(currentState); 
      } 
     } 
     while(/* do some times */); 
    } 
} 

public class Starter { 
    public static void main(final String[] args) { 
     final ApplicationContext context = // ...; 

     if(uiShouldBedisabled(args)) { 
      // remove the UI Service Bean 
     } 

     context.getBean(Businesslogic.class).startCalculation(); 
    } 
} 

回答

3

根據您的描述,你要在啓動時禁用這些豆子,而不是在任何時間任意點 - 這是更難。

@Profile

最簡單的方法是使用Spring @Profiles(可用自3.1),選擇性地啓用和禁用豆類:

@Service 
@Profile("gui") 
public class UI extends JFrame implements EventListener 

現在你需要告訴您要使用的配置文件的應用程序上下文。如果gui配置文件已激活,則將包含UI bean。如果不是,Spring將跳過該類。有多種方法來更改配置文件名稱,例如:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); 
if(!uiShouldBedisabled(args)) { 
    ctx.getEnvironment().setActiveProfiles("gui"); 
} 
ctx.scan("com.example"); 
ctx.refresh(); 

獨立JAR

分裂您的應用程序,以兩個JAR - 你的業務邏輯和GUI。如果你不想啓動GUI,只需從CLASSPATH中刪除gui.jar(是的,這在運行時是不可能的,但在構建/部署期間是不可能的)。

兩個applicationContext.xml文件

如果您的應用程序從XML開始,創建applicationContext.xmlapplicationContext-gui.xml。顯然,所有的GUI bean都在後者中。您不必手動指定它們,只需將GUI Bean放入不同的包中並添加巧妙的<context:component-scan/>即可。

相關問題