依赖 Spring 的注解 [英] Dependency on Spring's annotations

查看:40
本文介绍了依赖 Spring 的注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用@Repository、@Resource、@Component、@Service 注释对我的类进行了注释,但这些类必须在 2 个环境中运行.第一个环境基于 Spring 2.x,而另一个环境根本没有 spring.我敢肯定,没有 spring jars & 代码会失败.我想从您那里了解有关如何保留注释但仍然在两种环境中工作的想法

I have annotated my classes with @Repository, @Resource, @Component, @Service annotations but these classes must run in 2 environments. The first environment is Spring 2.x based while the other has no spring at all. I'm sure the code will fail without the spring jars & I want to know ideas from you on how I can retain the annotations but still work in both environments

推荐答案

由于您无法删除已接受的帖子,我建议您阅读/投票 Hans 的帖子,这比我原来的解释要好得多:对Spring注解的依赖

Since you cannot delete an accepted post, I suggest you read/vote Hans' post, which is a much better explanation than my original one: Dependency on Spring's annotations

当使用构造型注释(@Service 等)时,获得编译时 bean 验证的权衡是您在代码中与 spring-context 库耦合.我看到 3 个即时选项:

When using the stereotype annotations (@Service etc), the trade-off for gaining the compile-time bean validation is that you become coupled to the spring-context library in your code. I see 3 immediate options:

1) 删除注释,并在 XML 中配置您的 bean.

1) Remove the annotations, and configure your beans in XML.

2) 将 spring-context.jar(或保存构造型注释的等效库)复制到您的非 Spring 项目中以解决依赖关系,但不要配置 Spring,因此它不会在您的代码中使用.

2) Copy the spring-context.jar (or the equivalent library holding your stereotype annotations) into your non-Spring project to resolve the dependencies, but leave Spring unconfigured so it is not used in your code.

3) 从具体类中删除注释,并使用Spring"版本扩展它们.这种方法可能会或可能不会对您的设计有点侵入性,但值得考虑:

3) Remove the annotations from your concrete classes, and extend them with "Spring" versions. This approach may or may not be a little invasive to your design, but worth considering:

public class MyDAO {
    protected SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    // .. Your DAO code resides here ..
}

和 Spring 子类:

And the Spring sub-class:

@Repository
public class MySpringDAO extends MyDAO {

    @AutoWired
    protected SessionFactory sessionFactory;
}

这样,您的非 Spring 项目可以使用MyDAO",并从构建中排除MySpringDAO"类.

This way, your non-Spring project can use "MyDAO", and exclude the "MySpringDAO" class from the build.

这篇关于依赖 Spring 的注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆