如何在运行或启动时在Spring中禁用服务?

问题描述:

在我们的独立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(); 
    } 
} 

根据您的描述,你要在启动时禁用这些豆子,而不是在任何时间任意点 - 这是更难。

@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/>即可。