简体   繁体   English

如何将非Spring客户端与基于Spring的jar的配置脱钩?

[英]How can I decouple a non-Spring client from the configuration of a Spring-based jar?

I have only limited experience with Spring but am working with someone who really likes it. 我在Spring方面的经验有限,但正在与非常喜欢它的人一起工作。 We've built a set of packages that use Spring heavily and now we need to provide an access layer that exposes that functionality to clients that may not use Spring. 我们已经构建了一组大量使用Spring的软件包,现在我们需要提供一个访问层,向不使用Spring的客户端公开该功能。

My primary goal is that clients of the access layer should not be required to configure Spring in order to use it. 我的主要目标是不要求访问层的客户端配置Spring即可使用它。 Obviously Spring will be on the deployment classpath. 显然,Spring将位于部署类路径上。 In an ideal world, the client could build against the access layer package and deploy without knowing that Spring is being used. 在理想的情况下,客户端可以在不知道使用Spring的情况下根据访问层软件包进行构建和部署。 Is this possible? 这可能吗? (No, using a remote service is not an option.) (不,不能选择使用远程服务。)

As you don't want to have to write a load of new code that essentially wires up your application the same way spring already does it, is it possible you could hide all of this behind some sort of "facade" class that you will give to your client? 由于您不需要编写大量的新代码,而这些代码本质上可以像spring那样用相同的方式连接您的应用程序,是否有可能将所有这些隐藏在您将要提供的某种“ facade”类后面给你的客户?

For example, say I had a spring context that sets up ServiceA and ServiceB (these are the services that the client wants to access) 例如,假设我有一个设置ServiceAServiceB的spring上下文(这些是客户端要访问的服务)

I could write some classes like this... 我可以写一些这样的类...

public interface ClientServiceFacade {
    ServiceA getServiceA();

    ServiceB getServiceB();

    void shutdown();
}

public class ClientServiceFacadeFactory {
    public static ClientServiceFacade create() {
        return new ClientServiceFacadeImpl();
    }
}

public class ClientServiceFacadeImpl implements ClientServiceFacade {
    private static final CONTEXT_LOCATION = "classpath:spring/context.xml";

    private ClassPathXmlApplicationContext context;

    public ClientServiceFacadeImpl() {
        context = new ClassPathXmlApplicationContext(CONTEXT_LOCATION);
    }

    @Override
    public ServiceA getServiceA() {
        return context.getBean(ServiceA.class);
    }

    @Override
    public ServiceB getServiceB() {
        return context.getBean(ServiceB.class);
    }

    @Override
    public void shutdown() {
        context.close();
    }
}

Your clients will still have to include the spring JAR as a dependency, but (apart form that) they would have no idea that Spring is being used in the background. 您的客户仍将必须包含spring JAR作为依赖项,但是(除了那形式)他们不知道在后台使用Spring。

如何在静态块或静态init方法(如果要从外部触发)上初始化Spring上下文,或在守护进程线程上启动呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM