3

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

要禁用 UI,只需“删除”UI Bean 上的所有内容就足够了,@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();
    }
}
4

1 回答 1

6

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

@Profile

最简单的方法是使用Spring @Profile从 3.1 开始可用),选择性地启用和禁用 bean:

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

现在您需要告诉您的应用程序上下文您要使用哪个配置文件。如果gui配置文件被激活,UIbean 将被包括在内。如果没有 - Spring 将跳过该课程。有多种方法可以更改配置文件名称,例如:

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

单独的 JAR

将您的应用程序拆分为两个 JAR - 您的业务逻辑和 GUI。如果您不想启动 GUI,只需gui.jar从 CLASSPATH 中删除(是的,这在运行时是不可能的,但在构建/部署期间是不可能的)。

两个applicationContext.xml文件

如果您的应用程序从 XML 开始,请创建applicationContext.xmlapplicationContext-gui.xml. 显然所有的 GUI bean 都属于后者。您不必手动指定它们,只需将 GUI bean 放在不同的包中并添加聪明<context:component-scan/>的 .

于 2012-08-17T16:13:23.923 回答