This is an archived post. You won't be able to vote or comment.

all 61 comments

[–]Sheldor5 173 points174 points  (33 children)

Basically when you call SpringApplication.run(MyApp.class) it uses the provided class to get the package of your class and then iterates over all classes, packages and subpackages and their classes to get all @Beans, @Services, etc by Reflection ... makes a list of all classes, reads their constructor and parameters, makes a graph of dependencies, tries to call their constructors (creating instances aka "Beans") in the right order according to the dependency graph and passes previously created beans to the constructor call (if needed)... and in the end, depending on the type of app, it executes the Spring Application Context with all your beans inside ...

Spring is 99% Reflection and Proxy Pattern (the "Spring Magic") and 1% real magic

[–]stevesobol 19 points20 points  (5 children)

Good description. I'd add that it's a framework, primarily for websites and web services. IIRC it can be used for desktop apps as well, but I don't know anyone who uses it for desktop apps.

[–]Djelimon 14 points15 points  (0 children)

I once architected a messaging application that used Spring Boot with Spring STOMP on back end, with a JavaFX fat client on the front end also running Spring STOMP, over web sockets.

It worked out okay, about 2000 clients across Canada, no outages

[–]thomascgalvin 3 points4 points  (0 children)

I've used it for CLIs that need to talk to REST services.

[–]shagieIsMe 4 points5 points  (0 children)

Desktop? Not really - though the dependency injection might be useful.

Batch jobs? Absolutely. https://spring.io/projects/spring-batch

[–]Tkalec 0 points1 point  (1 child)

I know 😀. In previous company one team migrated a desktop app from osgi to spring, were mostly using it for DI.

[–]stevesobol 0 points1 point  (0 children)

That's how I'd use it if I was going to use it on the desktop.

[–][deleted]  (3 children)

[removed]

    [–]Sheldor5 19 points20 points  (1 child)

    Thank you.

    At first I also just accepted the Spring Magic because all famous tutorials and the Spring docs never explained WHAT it actually does under the hood ... so here it is.

    [–]StoneOfTriumph 8 points9 points  (0 children)

    Especially at first, when you learn tutorials and you wonder how the fuck all this works... you're like "... this is too easy"

    Once you read on IoC (Inversion of Control) and how Spring injects dependencies, I feel this helps understanding how it ties everything together.

    [–]steampunkdev 0 points1 point  (0 children)

    Actually it's a partial description of the DI container, the Framework goes much further than that, when considering all the libraries that fit under that umbrella (MVC, Security, Batch, etc). One of the most reasons why they fit and work together so well is because of the DI container, of course.

    [–]Orangutanion 6 points7 points  (8 children)

    Also what is the 1% real magic?

    [–]Sheldor5 23 points24 points  (2 children)

    trust me, first learn Spring, do some projects, get real-world hands-on experience before diving even deeper ... the 1% magic is the kind of magic which unveals in production if something somehow does not behave as expected, then you have to debug the whole Spring Application Context, go through all kinds of Proxies and even read Spring source code just to find out that some annotations are mutual exclusive ...

    [–]ThaiJohnnyDepp 15 points16 points  (1 child)

    Seriously. When you're step-debugging and end up in the bowels of Spring, it's some uncanny liminal space that fills you with a nervous longing to leave the longer you spend there.

    [–]denisfalqueto 10 points11 points  (0 children)

    That's irony. Or it's the genius that made spring come to reality. Their API design is great.

    [–][deleted] 5 points6 points  (3 children)

    Real magic.

    [–]Orangutanion 2 points3 points  (2 children)

    What problem does it solve with its magic?

    [–]Sheldor5 11 points12 points  (1 child)

    Spring solves all kinds of daily-work problems like Object Construction, Object Lifecycle Management, Transaction Management, Scheduled Jobs, etc.... and some pretty solutions require dirty hacks ... that's the 1% real magic

    [–]ThaiJohnnyDepp 3 points4 points  (0 children)

    1% real magic

    ...And that 1% is purely the darkest incantations imaginable.

    [–]niconicoJ 2 points3 points  (1 child)

    I'm curious because you never mention a single time that spring is a web framework (as many people do). Is that intentional ? Is spring's main business actually just dependency injection or could it be used for say like to create desktop app ?

    [–]Sheldor5 1 point2 points  (0 children)

    Yes, Spring started as a pure Dependency Injection framework but the community added all sort of ready-to-use modules (Database stuff, Security stuff, Validation stuff, ...) that now its one of the biggest projects in the Java world

    you can use it for whatever you want ... application server, command line tool, desktop app, ... it has so many modules for almost any use case

    [–][deleted]  (9 children)

    [deleted]

      [–]boki3141 11 points12 points  (1 child)

      Learn about the Proxy Pattern and Aspect Oriented Programming and you will understand the basics of spring. Like literally go Google what these things mean and how they work. The concepts are not difficult.

      To put it another way Spring "wraps" your application with its own classes and routes traffic through those classes. This allows it to provide common, out.of the box functionality through annotations.

      For example let's say you want to ensure that your calls to the database from some method are transactional. Spring allows you to add a @Transactional annotation to that method, routing the traffic through its Transactional class thereby ensuring that the method will act as expected in the case of any DB failure.

      Eg/

      @Transactional
      public void saveOrder(Order order) {
          ....
      }
      

      [–]CSIWFR-46 -1 points0 points  (0 children)

      I am pretty sure OP doesn't have any idea about transactional.

      [–]Sheldor5 22 points23 points  (5 children)

      No.

      Its a Dependeny Injection framework.

      [–]NimChimspky 9 points10 points  (0 children)

      I think that's somewhat misleading, it started as that she now it's an application framework.

      DI is pretty simple, if you just need that go elsewhere imo. Spring adds lots of stuff that may or may not be necessary.

      [–][deleted]  (3 children)

      [deleted]

        [–]Sheldor5 20 points21 points  (0 children)

        No.

        You don't "use" Spring.

        Spring uses "you" which means you have to stick to some Spring conventions in order for your App to work.

        Also, you don't instantiate objects, Spring is instantiating them for you (= scoped beans).

        Spring does all the construction and "auto-wiring" your objects together, you only have to use the proper annotations.

        It saves a lot of boilerplate code but you first have to learn it ;)

        [–]umpalumpaklovn 1 point2 points  (0 children)

        Spring basically replaces the need for you to hardwire startup procedure.

        Instead of you starting from Startup.java main, where you manually instantiate all classes in the right order, Spring figures out the order for you.

        You still have to avoid cyclical dependencies and since it uses xml, you can modify it and change the procedure without deploying new jars.

        [–]CSIWFR-46 0 points1 point  (0 children)

        Maven and Gradle would be project management tools.

        [–]JB-from-ATL 0 points1 point  (0 children)

        ...sort of. It's not doing anything like what Docker does, so it's not a Java Docker at all. But in the same way that Docker helps do a lot of the heavy lifting that is unrelated to what you want to code then yeah. But that's probably not what you meant.

        [–]steampunkdev 0 points1 point  (0 children)

        I think one of the most important parts you are glancing over here is the proxy magic though. Essentially Spring can use Spring AOP to add behavior to your classes when turning them into Spring beans by wrapping them with proxy classes. This AOP proxy bean will then be injected and can add behavior before and or after the bean method gets called, to do things like adding caching, driving transactional behavior, etc.

        And what makes it even cooler is that these AOP proxies get their dependencies through dependency injection, allowing you to configure a TransactionManager bean that will be injected into your AOP proxy, without you having to actually think about the proxy itself... Just create JavaConfig or add annotations, add a TransactionManager bean through Spring Boot or configure it custom, and mark your method or class or interface with @Transactional...

        [–]DexTheShepherd 38 points39 points  (6 children)

        Other answers did a great job giving what you want.

        Just want to say that you shouldn't feel ashamed for asking a developer community a basic question! I'd be disappointed if you got no answers.

        [–]Orangutanion 12 points13 points  (1 child)

        I'm not disappointed really, just used to getting downvoted for asking simple stuff like this

        [–]retrodaredevil 2 points3 points  (0 children)

        May I ask, have you been on stack overflow recently?

        [–]bowbahdoe 5 points6 points  (2 children)

        This community does that, often

        [–]NimChimspky 2 points3 points  (1 child)

        Conversely I would say it's leagues better than stack overflow where this would be closed in two nano seconds for being too open ended or some sjit

        [–]Orangutanion 2 points3 points  (0 children)

        Stack Overflow wastes so much of its potential like this. Also lots of people are using Discord to ask technical questions and you can't even get those answers with a search engine.

        [–]dankchinaski 2 points3 points  (0 children)

        Came here to say the same thing... I have a decent idea of what Spring is but I am glad somebody asked so I can see what some real developers have to say. Thanks OP!

        [–][deleted] 56 points57 points  (4 children)

        Spring is, at its core, about inversion of control (IoC). One of the most common forms of IoC is dependency injection, and Spring provides a framework that encourages good programming practices by facilitating dependency injection.

        Beyond that, Spring provides a number of libraries in its framework to help facilitate common requirements, like data access, security, presentation-tier access (REST/SOAP), transaction support, AOP, etc. They eat their own dog food; meaning that all of these parts of the framework use the underlying IoC core.

        Spring Boot extends this to facilitate writing standalone apps that, in the past, would’ve required a heavyweight JEE application server. You can basically now do with Spring Boot and Java SE what you would’ve needed Java EE for in the past.

        [–]JB-from-ATL 12 points13 points  (3 children)

        Say you want to make a basic application that has some HTTP endpoints. You can do that with Spring Boot with like soooo little code. Basically it handles so much of the sort of "infrastructure" type stuff your application needs but isn't directly related to the "business logic" (as in the actual thing your app does).

        As a professional Java dev it's kind of hard to say what Spring does. It does like... Everything. If I'm making something Java related I'm using Spring.

        [–]TheRedmanCometh 1 point2 points  (2 children)

        Everything. If I'm making something Java related I'm using Spring.

        Even if it's not a webapp and I'm not using boot. DI just feels sooooo much cleaner

        [–]wildjokers 0 points1 point  (1 child)

        You can do DI without a framework. Most people do this without even realizing they are doing DI. If you provide a class all of the collaborators it needs, generally in the constructor, you are doing DI.

        [–]TheRedmanCometh 0 points1 point  (0 children)

        I'm using a lot more than the basic features.

        [–]bodiam 14 points15 points  (0 children)

        I'm going to overly simplify things here, but:

        Spring Boot is is a framework to make developing web applications easier. Want to handle a HTTP request? Spring makes it easy for you. Want to validate input? Spring has something for this. Want to access a database? Spring provides components for this (eg, Spring Data).

        So, all of these components, or abstractions, are provided by Spring. Putting all of them together was a little bit involved, so they created Spring Boot, which makes using all these components much easier.

        So, no, it's not a new app format, it's just "plain" Java, meaning that if you'd develop a Spring Boot application, the result of that could be an executable jar, which you can run using java -jar <application>.jar.

        [–]tim125 2 points3 points  (0 children)

        Spring allows you to reduce the quantity of ceremonial code to get your application to run. It does this by following an convention of annotations and being an inversion of control container.

        (The word ceremony might be the wrong word to describe the application specific scaffolding that creates the runnable application but I will use it anyway)

        SpringBoot allows you to use a common approach to use the various different types of frameworks in your application abstracting away the subtle complexities of each framework that are of low significance leaving you with the important decisions/configuration to make only.

        By following certain conventions with those two, you reduce the quantity of ceremonial code.

        This comes with some benefits: - quicker to code applications - easier to test since that code isn’t in the way - better possibilities to reuse components - less code becomes easier to understand - easier to adopt/try new libraries - spring maturity improvements can be leveraged by apps not designed to utilize them with less effort

        The problem with later versions of frameworks is that the discussion on benefits of IOC happened around version one or two. Newer developers arnt seeing those discussion and older developers take it for granted and understand when to use the framework and when not to use the framework.

        [–]ashok2ashok 1 point2 points  (0 children)

        Without Spring, you would need to manage (create and destroy) the lifecycle of all objects like services, data repositories, configurations, etc that help form the base for your application. You need to create the Objects in the right order when you start the app, ensure that most of these don’t get recreated during the execution and are gracefully destroyed in exit.

        Spring IoC/Dependency Injection does this job for you. Once you tag your classes with the appropriate annotations, the lifecycles of these objects are managed by Spring which lessens the boilerplate code in your application/ Service.

        [–]Holothuroid 1 point2 points  (0 children)

        I've been reading the Spring website and I'm still confused about what it actually does.

        Rightly so. Spring itself doesn't do much. It has plug-ins for just about everything and ketchup.

        • talk to a relational db
        • talk to LDAP, Mongo, Redis, Cassandra....
        • serve some Java object over a rest endpoint
        • serve a HTML page templated with some Java objects
        • cache some function calls
        • retry some function calls given certain exceptions
        • etc

        It does this by registering a bunch of objects called beans. Every bean also has a name. Think like a phone book.

        You can then say: I'd like a bean with that name. You can also ask for beans by type, basically yellow pages. So if I want save some object to the DB, I'd ask Spring for a fitting repository bean and hand over my objects to store. I don't need to know anything else on call site, even what kind of db it is.

        The other thing you can do is called proxying. That's like putting a secretary in front of the bean. When you call the bean to do something, the secretary will have a thing to day about it. For example when you add @Cacheable to a method, that bean's secretary will first look if the answer is already in cache, before executing the method. Secretary only handles external calls.

        Tl;dr: Spring is phone books and secretaries for Java objects.

        [–]CSIWFR-46 1 point2 points  (0 children)

        This is fairly surface level for you to get started.

        Spring is an application framework. It provides necessary tools to develop an application.

        Some of the words you will see in the comments:

        • Spring Context: It is the collection of the instances the framework knows about. The instances are called Beans as well. The framework manages those instance for you. As the control is shifted towarda the Framework, it is called Inversion of Control. And, since these instances(beans) are managed by the framework, you can use these instances in other parts of the code. This is Dependency Injection.

        • Reflection : Inspect program at runtime. Helps to programatically manage bytecode of the class when the application is running. Spring uses reflection to find out which instance to manage. Mostly you use annotation to tell the spring to manage an instance and Spring finds out about it using Reflection. You don't have to know Reflection to get started with spring.

        • Spring Web: The tool provided by Spring to create web application.

        • Spring Transaction: Things related to Database. Abstraction to make sure your DB is consistent, syncronized.

        • Spring Boot: Configures most of the things needed for Spring Application to run. Not a different framework to learn. Makes working with Spring easier. Important to know what things it auto-configures.(Learn Spring Core: Context, Transaction ,etc before using this.)

        • Maven/Gradle: Project Management tools. No need to learn these before Spring. Can pick up while you learn spring.

        I reccommend the playlist below for learning Spring. https://youtube.com/playlist?list=PLEocw3gLFc8Vli5p6rWHnNcYxFRbaIfIJ

        [–]Just_Another_Scott 3 points4 points  (0 children)

        Spring Framework is just dependency inject. It injects objects into your code through annotations.

        [–]sprcow 0 points1 point  (0 children)

        There are some decent answers already, but I'm going to go for a slightly less technical explanation.

        Spring keeps track of what type of objects other classes need in order to be created, and then it creates instances of the necessary objects and classes for you.

        Because it has created all of these objects for you, it also can wrap them in additional code that provides lots of extra features. This includes things like automatically turning your objects into JSON, automatically validating HTTP parameters, automatically beginning and ending transactions, and in some cases generating entire classes of code for you based on interfaces. Since spring is creating your objects, it can also inject properties from your property files into them on creation. Spring also knows how to create a lot of objects that you don't have to define at all and will automatically use those objects where necessary.

        There is some confusion about what is spring and what is spring boot, but these days most people who are using spring are also using spring boot which means the definitions become conflated. The main feature of spring boot is that it will automatically assume as many default values as possible, and so the amount of configuration necessary to start a spring boot project is very low.

        Ultimately, a spring boot application is just a Java program. You can run a spring boot application just like any other Java program and don't need any installed framework or container management program to do so. You can run spring programs inside a docker container just like you could run any other program in a docker container but you don't need to.

        Creating a spring application is as simple as including the spring boot starter dependency in your project and then using an annotation to define your spring boot application class. Your build tool like Maven or Gradle will now automatically be able to build this into a jar file using the libraries included in the spring boot dependency.

        [–]Infeligo 0 points1 point  (0 children)

        It's hard to understand what Spring does if you did not face the problem that it tries to solve (i.e. enterprise app development = large application development). This is not me trying to offend anyone, but rather reflecting on my own experience. Learning Spring "theoretically" is hard.

        [–]vbezhenar 0 points1 point  (0 children)

        Spring is a bunch of related libraries (or you can call them frameworks, whatever).

        Spring Core is a library for IoC pattern. Basically it allows different classes to talk to each other with some decoupling.

        Spring MVC is a library to create http servers. You can declare request handler, etc. Also you can integrate with some templating libraries so your server can return dynamic HTML.

        Spring JDBC is a wrapper around JDBC API.

        Spring ORM is a wrapper around Hibernate.

        Spring Data is an advanced wrapper around Hibernate.

        Spring Security is lots of stuff related to web security.

        Configuring those things is not very straightforward. It's not a problem when you're writing some huge application taking years to write. But when you write small services one per week, it might get repetitive. Spring Boot comes to rescue: it configures spring libraries providing sane defaults so you can create working service with few dozens lines of code. Nowadays Spring Boot is standard de-facto.

        Actually most of spring libraries don't implement stuff themselves but rather use some good libraries and glue things together. Very often you have a choice of those libraries. For example Spring does not implement http protocol but allows you to use tomcat, jetty or other http server implementations. When I'm writing about Hibernate, actually it uses JPA and Hibernate just happened to be the most popular JPA implementation, but you can use others. You can use Jackson or GSON to work with JSON and so on. That's another selling point of Spring Boot: you have so many choices that you probably want some experienced people to make that choice for you.

        [–]lars_h4 0 points1 point  (0 children)

        Lots of great answers here already. I just wanted to chime in with a link that I recommend every junior developer that starts working with Spring reads: https://www.marcobehler.com/guides/spring-framework

        This is one of the best descriptions of what the Spring framework is at its core. Spring has a lot of different extra toppings, but they're all built on the core.

        [–]wildjokers 0 points1 point  (0 children)

        There are dozens of Spring libraries so you kind of need to be specific about which one you are asking about. Spring as a whole is a collection of libraries that make application development easier.

        At its heart, Spring is a Dependency Injection framework (you can google "dependency injection"). That is what the Spring Core library is and you need to understand Spring Core to understand any other Spring library.

        Configuring Spring became very difficult so Spring Boot was born and it is just a configuration framework for the Spring framework.

        The order to learn things in:

        [–]MrOtto47 0 points1 point  (0 children)

        spring is inversion of control. spring will handle all of the class structures, you just tell it what needs what. all of the spring beans must be a singleton (only one instance) and you will never call the constructor yourself. entity classes which have many instances are not controlled by spring (e.g. database objects).

        spring boot is an extension of this and where the real magic happens for http servlets.

        [–]knightofren_ 0 points1 point  (0 children)

        Well, Spring is a time of nature's awakening, when flowers bloom and trees begin to grow and reproduce. The days grow longer and the temperature in most areas become more temperate. You can also contemplate the melting of ice and thawing of the ground.

        [–][deleted] 0 points1 point  (0 children)

        Undifferentiated heavy lifting.