如何在Spring中在运行或启动正常运行时间时禁用服务



在我们独立的Spring 3.1应用程序中,我们严格地将业务逻辑与Monitoring Swing View分开。视图通过实现EventListener接口来获取其信息。

要禁用UI,只需"删除"UIBeans上的所有@Services就足够了,这样实现该EventListner的UI类就不会被业务逻辑注入。

但是如何做到这一点呢?

这个例子给出了我们类的一个小视图:

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

根据您的描述,您希望在启动时禁用这些bean,而不是在任何任意时间点禁用,这要困难得多。

@Profile

最简单的方法是使用Spring @Profile s(自3.1起可用),选择性地启用和禁用beans:

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

最新更新