Java Spring 框架到底是做什么用的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1061717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:58:06  来源:igfitidea点击:

What exactly is Spring Framework for?

javaspringframeworks

提问by Maksim

I hear a lot about Spring, people are saying all over the web that Spring is a good framework for web development. What exactly is Spring Framework for?

我听到很多关于Spring 的消息,网上到处都在说 Spring 是一个很好的 Web 开发框架。Spring 框架到底是做什么用的?

采纳答案by victor hugo

Basically Spring is a framework for dependency-injectionwhich is a pattern that allows to build very decoupled systems.

Spring 基本上是一个依赖注入框架,它是一种允许构建非常解耦系统的模式。

The problem

问题

For example, suppose you need to list the users of the system and thus declare an interface called UserLister:

例如,假设您需要列出系统的用户并因此声明一个名为 的接口UserLister

public interface UserLister {
    List<User> getUsers();
}

And maybe an implementation accessing a database to get all the users:

也许是访问数据库以获取所有用户的实现:

public class UserListerDB implements UserLister {
    public List<User> getUsers() {
        // DB access code here
    }
}

In your view you'll need to access an instance (just an example, remember):

在您看来,您需要访问一个实例(请记住,这只是一个示例):

public class SomeView {
    private UserLister userLister;

    public void render() {
        List<User> users = userLister.getUsers();
        view.render(users);
    }
}

Note that the code above doesn't have initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:

请注意,上面的代码没有初始化变量userLister。我们应该做什么?如果我像这样显式实例化对象:

UserLister userLister = new UserListerDB();

...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case I would go to my code again and change the last line by:

...我会将视图与访问数据库的类的实现结合起来。如果我想从 DB 实现切换到另一个从逗号分隔的文件中获取用户列表的实现怎么办(请记住,这是一个示例)?在这种情况下,我会再次转到我的代码并通过以下方式更改最后一行:

UserLister userLister = new UserListerCommaSeparatedFile();

This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes. The maintenance becomes a nightmare!

这对于像这样的小程序来说没有问题,但是......在具有数百个视图和相似数量的业务类的程序中会发生什么。维护变成了一场噩梦!

Spring (Dependency Injection) approach

Spring(依赖注入)方法

What Spring does is to wirethe classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injectedin the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).

什么春天确实是来连线通过使用XML文件或注解,这样所有的对象实例化和春天初始化和班达注射在适当的地方(Servlet的Web框架,业务类,DAO的,等,等,等……)。

Going back to the example in Spring we just need to have a setter for the userListerfield and have either an XML file like this:

回到 Spring 中的示例,我们只需要为该userLister字段设置一个 setter并有一个像这样的 XML 文件:

<bean id="userLister" class="UserListerDB" />

<bean class="SomeView">
    <property name="userLister" ref="userLister" />
</bean>

or more simply annotate the filed in our view class with @Inject:

或者更简单地用以下内容注释我们视图类中的文件@Inject

@Inject
private UserLister userLister;

This way when the view is created it magicallywill have a UserListerready to work.

当视图被创建这样奇迹般地将有一个UserLister准备工作。

List<User> users = userLister.getUsers();  // This will actually work
                                           // without adding any line of code

It is great! Isn't it?

太好了!不是吗?

  • What if you want to use another implementation of your UserListerinterface?Just change the XML
  • What if don't have a UserListerimplementation ready?Program a temporal mock implementation of UserListerand ease the development of the view
  • What if I don't want to use Spring anymore?Just don't use it! Your application isn't coupled to it. Inversion of Controlstates: "The application controls the framework, not the framework controls the application".
  • 如果您想使用UserLister接口的另一个实现怎么办?只需更改 XML
  • 如果没有UserLister准备好实施怎么办?UserLister对视图的时间模拟实现进行编程并简化视图的开发
  • 如果我不想再使用 Spring 怎么办?只是不要使用它!您的应用程序没有与之耦合。控制反转状态:“应用程序控制框架,而不是框架控制应用程序”。

There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.

那里还有一些其他的依赖注入选项,在我看来,除了简单、优雅和稳定之外,让 Spring 如此出名的原因是 SpringSource 的人已经编写了许多 POJO,这些 POJO 有助于将 Spring 与许多其他常见框架集成而不会被侵入您的应用程序。此外,Spring 有几个不错的子项目,如 Spring MVC、Spring WebFlow、Spring Security 以及大量的其他项目。

Hope this helps. Anyway, I encourage you to read Martin Fowler's articleabout Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look to Spring Documentation, in my opinion it isused to bethe best Spring book ever.

希望这可以帮助。不管怎样,我鼓励你阅读Martin Fowler关于依赖注入和控制反转的文章,因为他比我做得更好。了解基础知识去看一下后Spring文档,在我看来,这曾经是最好的春季书永远。

回答by stevedbrown

Spring is great for gluing instances of classes together. You know that your Hibernate classes are always going to need a datasource, Spring wires them together (and has an implementation of the datasource too).

Spring 非常适合将类的实例粘合在一起。你知道你的 Hibernate 类总是需要一个数据源,Spring 将它们连接在一起(并且也有一个数据源的实现)。

Your data access objects will always need Hibernate access, Spring wires the Hibernate classes into your DAOs for you.

您的数据访问对象将始终需要 Hibernate 访问,Spring 将 Hibernate 类连接到您的 DAO 中。

Additionally, Spring basically gives you solid configurations of a bunch of libraries, and in that, gives you guidance in what libs you should use.

此外,Spring 基本上为您提供了一堆库的可靠配置,并在其中为您提供了应该使用哪些库的指导。

Spring is really a great tool. (I wasn't talking about Spring MVC, just the base framework).

Spring确实是一个很棒的工具。(我不是在谈论 Spring MVC,只是在谈论基础框架)。

回答by Priyank

Spring contains(as Skaffman rightly pointed out) a MVC framework. To explain in short here are my inputs. Spring supports segregation of service layer, web layer and business layer, but what it really does best is "injection" of objects. So to explain that with an example consider the example below:

Spring包含正如 Skaffman 正确指出的那样)一个 MVC 框架。简而言之,这里是我的投入。Spring 支持服务层、Web 层和业务层的分离,但它真正做得最好的是对象的“注入”。因此,要通过示例来解释这一点,请考虑以下示例:

public interface FourWheel
{
   public void drive();
}

public class Sedan implements FourWheel
{
   public void drive()
   {
      //drive gracefully
   }
}

public class SUV implements FourWheel
{
   public void drive()
   {
      //Rule the rough terrain
   }
}

Now in your code you have a class called RoadTrip as follows

现在在您的代码中,您有一个名为 RoadTrip 的类,如下所示

public class RoadTrip
{
    private FourWheel myCarForTrip;
}

Now whenever you want a instance of Trip; sometimes you may want a SUV to initialize FourWheel or sometimes you may want Sedan. It really depends what you want based on specific situation.

现在只要你想要一个 Trip 的实例;有时您可能需要 SUV 来初始化 FourWheel,有时您可能需要 Sedan。这真的取决于您想要什么,具体取决于具体情况。

To solve this problem you'd want to have a Factory Pattern as creational pattern. Where a factory returns the right instance. So eventually you'll end up with lots of glue code just to instantiate objects correctly. Spring does the job of glue code best without that glue code. You declare mappings in XML and it initialized the objects automatically. It also does lot using singleton architecture for instances and that helps in optimized memory usage.

为了解决这个问题,你需要一个工厂模式作为创建模式。工厂返回正确实例的地方。所以最终你会得到大量的胶水代码,只是为了正确地实例化对象。Spring 在没有胶水代码的情况下最好地完成胶水代码的工作。您在 XML 中声明映射并自动初始化对象。它还对实例使用单例架构做了很多工作,这有助于优化内存使用。

This is also called Inversion Of Control. Other frameworks to do this are Google guice, Pico container etc.

这也称为控制反转。其他实现此目的的框架是 Google guice、Pico 容器等。

Apart from this, Spring has validation framework, extensive support for DAO layer in collaboration with JDBC, iBatis and Hibernate (and many more). Provides excellent Transactional control over database transactions.

除此之外,Spring 还具有验证框架、与 JDBC、iBatis 和 Hibernate(以及更多)协作的对 DAO 层的广泛支持。提供对数据库事务的出色事务控制。

There is lot more to Spring that can be read up in good books like "Pro Spring".

Spring 的更多内容可以在“Pro Spring”等好书中读到。

Following URLs may be of help too.
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework

以下网址也可能有帮助。
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article .tss?l=SpringFramework

回答by Pablojim

Spring started off as a fairly simple dependency injection system. Now it is huge and has everything in it (except for the proverbial kitchen sink).

Spring 最初是一个相当简单的依赖注入系统。现在它很大,里面什么都有(除了众所周知的厨房水槽)。

But fear not, it is quite modular so you can use just the pieces you want.

但不要害怕,它是非常模块化的,所以你可以只使用你想要的部分。

To see where it all began try:

要查看一切开始的地方,请尝试:

http://www.amazon.com/Expert-One-Design-Development-Programmer/dp/0764543857/ref=sr_1_1?ie=UTF8&s=books&qid=1246374863&sr=1-1

http://www.amazon.com/Expert-One-Design-Development-Programmer/dp/0764543857/ref=sr_1_1?ie=UTF8&s=books&qid=1246374863&sr=1-1

It might be old but it is an excellent book.

它可能很旧,但它是一本很棒的书。

For another good book this time exclusively devoted to Spring see:

对于这次专门介绍 Spring 的另一本好书,请参阅:

http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833/ref=sr_1_2?ie=UTF8&s=books&qid=1246374863&sr=1-2

http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833/ref=sr_1_2?ie=UTF8&s=books&qid=1246374863&sr=1-2

It also references older versions of Spring but is definitely worth looking at.

它还引用了旧版本的 Spring,但绝对值得一看。

回答by bpapa

What you'd probably want in a web application with Spring -

您可能在使用 Spring 的 Web 应用程序中想要什么 -

  • Spring MVC, which with 2.5+ allows you to use POJOs as Controller classes, meaning you don't have to extend from any particular framework (as in Struts or Spring pre-2.5). Controller classes are also dead simple to test thanks in part to dependency injection
  • Spring integration with Hibernate, which does a good job of simplifying work with that ORM solution (for most cases)
  • Using Spring for a web app enables you to use your Domain Objects at all levels of the application - the same classes that are mapped using Hibernate are the classes you use as "form beans." By nature, this will lead to a more robust domain model, in part because it's going to cut down on the number of classes.
  • Spring form tags make it easier to create forms without much hassle.
  • Spring MVC 2.5+ 允许您将 POJO 用作控制器类,这意味着您不必从任何特定框架进行扩展(如在 Struts 或 Spring 2.5 之前)。控制器类也非常容易测试,部分归功于依赖注入
  • Spring 与 Hibernate 的集成,可以很好地简化 ORM 解决方案的工作(对于大多数情况)
  • 将 Spring 用于 Web 应用程序使您能够在应用程序的所有级别使用域对象 - 使用 Hibernate 映射的相同类是您用作“表单 bean”的类。从本质上讲,这将导致更健壮的域模型,部分原因是它将减少类的数量。
  • Spring 表单标签使创建表单变得更容易,没有太多麻烦。

In addition, Spring is HUGE - so there are a lot of other things you might be interested in using in a web app such as Spring AOP or Spring Security. But the four things listed above describe the common components of Spring that are used in a web app.

此外,Spring 是巨大的 - 因此您可能有兴趣在 Web 应用程序中使用许多其他东西,例如 Spring AOP 或 Spring Security。但是上面列出的四件事描述了 Web 应用程序中使用的 Spring 的常见组件。

回答by fastcodejava

Spring is a good alternative to Enterprise JavaBeans (EJB)technology. It also has web framework and web services framework component.

Spring 是Enterprise JavaBeans (EJB)技术的一个很好的替代品。它还具有 Web 框架和 Web 服务框架组件。

回答by Johan

Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.

非常简短的总结,我会说 Spring 是您应用程序中的“粘合剂”。它用于集成不同的框架和您自己的代码。

回答by karstensrage

Spring is three things.

春天是三件事。

  1. Spring handles Dependency Injection and I recommend you read Martin Fowler's excellent introduction on dependency injection.
  2. The second thing Spring does is wrap excellent Java libraries in a very elegant way to use in your applications. For a good example see how Spring wraps Task Executors and Quartz Scheduler.
  3. Thirdly Spring provides a bunch of implementations of web stuff like REST, an MVC web framework and more. They figure since you are using Spring for the first two, maybe you can just use it for everything your web app needs.
  1. Spring 处理依赖注入,我建议您阅读 Martin Fowler 对依赖注入的出色介绍。
  2. Spring 所做的第二件事是以非常优雅的方式包装优秀的 Java 库,以便在您的应用程序中使用。一个很好的例子,看看 Spring 如何包装 Task Executors 和 Quartz Scheduler。
  3. 第三,Spring 提供了一系列 Web 内容的实现,例如 REST、MVC Web 框架等。他们认为,由于您在前两个中使用 Spring,也许您可​​以将它用于您的 Web 应用程序所需的一切。

The problem is that Spring DI is really well thought out, the wrappers around other things are really well thought out in that the other things thought everything out and Spring just nicely wraps it. The Spring implementations of MVC and REST and all the other stuff is not as well done (YMMV, IMHO) but there are exceptions (Spring Security is da bomb). So I tend to use Spring for DI, and its cool wrappers but prefer other stuff for Web (I like Tapestry a lot), REST (Jersey is really robust), etc.

问题是 Spring DI 真的经过深思熟虑,其他东西的包装也经过深思熟虑,因为其他东西都考虑到了一切,而 Spring 只是很好地包装了它。MVC 和 REST 的 Spring 实现以及所有其他东西都做得不好(YMMV,恕我直言),但也有例外(Spring Security 是炸弹)。所以我倾向于将 Spring 用于 DI 及其很酷的包装器,但更喜欢其他用于 Web 的东西(我非常喜欢 Tapestry)、REST(Jersey 非常健壮)等。

回答by Tom De Leu

I see two parts to this:

我看到了两个部分:

  1. "What exactly is Spring for" -> see the accepted answer by victor hugo.
  2. "[...] Spring is [a] good framework for web development" -> people saying this are talking about Spring MVC. Spring MVC is one of the many parts of Spring, and is a web framework making use of the general features of Spring, like dependency injection. It's a pretty generic framework in that it is very configurable: you can use different db layers (Hibernate, iBatis, plain JDBC), different view layers (JSP, Velocity, Freemarker...)
  1. “Spring 到底是什么”-> 参见 victor Hugo 接受的答案。
  2. “[...] Spring 是 [一个] 很好的 Web 开发框架”-> 人们说这是在谈论 Spring MVC。Spring MVC 是 Spring 的众多部分之一,是一个利用 Spring 的通用特性(如依赖注入)的 Web 框架。这是一个非常通用的框架,因为它非常易于配置:您可以使用不同的数据库层(Hibernate、iBatis、普通 JDBC)、不同的视图层(JSP、Velocity、Freemarker...)

Note that you can perfectly well use Spring in a web application without using Spring MVC. I would say most Java web applications do this, while using other web frameworks like Wicket, Struts, Seam, ...

请注意,您可以在 Web 应用程序中很好地使用 Spring,而无需使用 Spring MVC。我会说大多数 Java Web 应用程序都这样做,同时使用其他 Web 框架,如 Wicket、Struts、Seam ......

回答by Ash

What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.

春天有什么用?我将很快回答这个问题,但首先,让我们再看一下 victor Hugo 的例子。这不是一个很好的例子,因为它不能证明需要一个新框架。

public class BaseView {
  protected UserLister userLister;

  public BaseView() {
    userLister = new UserListerDB(); // only line of code that needs changing
  }
}

public class SomeView extends BaseView {
  public SomeView() {
    super();
  }

  public void render() {
    List<User> users = userLister.getUsers();
    view.render(users);
  }
}

Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!

完毕!所以现在即使您有成百上千的视图,您仍然只需要更改一行代码,就像在 Spring XML 方法中一样。但是更改一行代码仍然需要重新编译,而不是您说编辑 XML?好吧,我挑剔的朋友,使用 Ant 和脚本吧!

So what is Spring for? It's for:

那么Spring是干什么用的呢?它是为了:

  1. Blind developers who follow the herd
  2. Employers who do not ever want to hire graduate programmers because they don't teach such frameworks at Uni
  3. Projects that started off with a bad design and need patchwork (as shown by victor hugo's example)
  1. 盲目跟风的开发者
  2. 不想雇用研究生程序员的雇主,因为他们不在大学教授此类框架
  3. 以糟糕的设计开始并需要拼凑的项目(如维克多雨果的例子所示)

Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12

进一步阅读:http: //discuss.joelonsoftware.com/?joel.3.219431.12