I've done some research on this, but still only have a vague understanding of it at best. Can anyone who is knowledgable on this give me a simple (or as simple as possible) description that someone with a basic understanding of programming could understand? Thanks for any help.
Spring was built on top of the idea of dependency injection and inversion of control. In normal words - instead of having a bunch of classes creating each other and passing each other from one place to another you have a bag of beans. Each bean declares its dependencies (what services do I need to work?) and Spring container resolves this requirements by automatically and automagically wiring everything together.
You have a Service that says (through XML, annotations, constructor signature...) I need DAO interface to work! and Spring is kind enough to find some bean that implements that interface, create it first and pass where it is required.
On that foundation multiple other services were provided (mostly in terms of data access and AOP), but the injection is the core concept.
If you want a quick and simple explanation then I can tell you that the heart of the Spring framework is the Inversion of control (IoC).
Naturally is reductive talk about Spring in 3 lines, but understand the IoC and you understand Spring. Everything is build around it in Spring.
Related
I’m taking this udemy course all about Spring Hibernate etc. The course started with explaining how Injection of Control and dependency injection works not in a web perspective just like having simple classes or beans, defining beans and their dependencies inside a config xml file or inside the actual class Using java annotation and then a main class where the beans are created. I understood that despite not really seeing the big benefit of using IoC and DI other than separating roles like creating and maintaining objects and adding dependencies the object needs and I guess when the project is bigger this makes it cleaner and easier to follow right?
However what I don’t understand is how IOC and DI ties in a full spring MVC project. Like I understand using the #Controller annotation means it’s like an #Component and you could make it scan the components automatically when it creates beans but like unlike before there isn’t a main class where beans are created and configured rather I have a controller class where I manually create objects and models and pass that back to the views where I can use the values in the model. I don’t see how I use IoC or DI here? Or is it because it’s a simple project and perhaps the objects we created didn’t have many dependencies?Or are a lot of the uses and implementation done internally or automatically?
I am just struggling to a) see why IoC and DI are that important and b) how are they actually used in a Spring MVC project where you don’t have a main class where you do create beans.
A) Create a project, but don't add any dependency (or web-mvc). Then do it yourself then see how much need time to create configure manually. If it is just a simple mvc project, you can do it manually, but if your project increase day by day then a huge configuration file to maintain your project properly. But when you are professional developer, you don't have so much time to configure all those manually. So here is come the solution IoC and DI. Controller or other anotation are configured in build-in jars. You don't have to worried about to create controller or to create bean, just use them when you neer them. It's save your time as well as headache about is it working or not. It's increase your productivity while your are working on a big project.
B) Yes, there is no main class in web project. To run a web project, you need a server. The server first looking for a configuration (In spring, it's web.xml, dispatcher-servlet). If it available then expand the configuration file, if not then throw an error. In that configuration file, explain everything about the web project. What should do, what is not mandatory, what is entry point etc.
So, IoC and DI are very important because to understand how a web project work behind the scene or how all component work together.
IoC is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application.
The advantages of this architecture are:
decoupling the execution of a task from its implementation
making it easier to switch between different implementations
greater modularity of a program
greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts
Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).
You can go with Annotation based configuration, where you can define #Configuration class and return the required beans using #Bean annotation.
Also you can use #Component to your POJO class to treat it as Spring bean.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm new to the spring framework. In most of the Spring tutorials I saw, Spring is described as "non-invasive".
What is meant by invasive? What are the merits of using Spring in Java and what makes it non-invasive?
If an IoC container is invasive, it means your code needs to be explicitly aware of dependency injection. For example, in Guice you use the #Inject annotation (and others). These annotations are more standardized than they used to be, which is good - it means with a single set of annotations you can (at least in theory) make your code available for use with various different invasive IoC containers.
With a non-invasive container, you can write your code with no reference to IoC at all... everything is just determined by reflection over members and annotations which would be present even if you weren't using IoC.
There are pros and cons of both invasive and non-invasive containers - being more specific in code can give you more control over some of the details of binding, for example - but it's worth being aware of the difference.
check http://forum.springsource.org/showthread.php?27846-Spring-is-non-invasive
What does it really means?
"You are not forced to import or extend any Spring APIs, example Struts forces you to extend Action".
Of course in some areas, such as the web framework, it's impossible to avoid aplication code depending on the framework. But Spring consistently attempts to reach the non-invasive ideal where configuration management is concerned
Most of the java frameworks force you to extend one of their classes or implement one of their interfaces. Example of such an invasive programming model was EJB 2-era stateless session beans, earlier versions of Struts, WebWork, Tapestry.
Spring avoids littering your code with its API. Spring never forces you to implement a Spring-specific interface or extend a Spring-specific class. Instead, the classes often don’t have any indication that they’re being used by Spring.
public class HelloWorld {
public String hello() {
return "Hello World";
}
}
This is a simple, Java class(POJO). Nothing indicates that it's a Spring component. Spring is non-invasive means this class could function equally well in a Spring application as it could in a non-Spring application. Although POJOs are simple they can be powerful.
One of the ways POJOs can become powerful in Spring is by using Dependency Injection.
Spring can be invasive and non-invasive, it's only up to you.
Non-invansive spring doesn't use annotations (for example #Autowired) nor its own classes (for example JdbcTemplate), it only uses configuration to wire your beans (simple POJO) together (you still have to initialize spring somehow in your code, which is a little bit invasive anyway). But you are free to drop spring without any significant code changes. Invasive spring, on the other hand, provides you template classes (for persistence, web services,...), annotations and other stuff you cannot simply leave behind without refactoring (if you use them).
EDIT: Some say spring is not invasive, because it doesn't force you to implement interfaces nor extend classes. For me a framework is not invasive, if it can be easily replaced.
An invasive framework means that you are force to extend one of their classes or implement one of their interfaces. You can see that in frameworks like Struts or EJB2. Spring is not-invasive because avoids that. At worst, a class may be annotated with one of Spring's annotation, but it´s otherwise a POJO. So only you need a POJO like that:
package com.habuma.spring;
public class HelloWorldBean {
public String sayHello() {
return "Hello World";
}
}
Spring framework is said to be a non-invasive means it doesn’t force a programmer to extend or implement their class from any predefined class or interface given by Spring API, in struts we used to extend Action Class right that’s why struts is said to be invasive.
In case of struts framework, it will forces the programmer that, the programmer class must extend from the base class provided by struts API.
Use #Resource and #Inject instead of #Component and #Autowired. It is really useful and is standardized across DI frameworks like Spring and Guice.
Invasive meaning - spreading very quickly all around. Spring author says frameworks like EJB, Struts etc are full of framework specific code which is hard to migrate to other frameworks which is against Java philosophy of write once and run anywhere.
Spring says it noninvasive because it uses POJO to write server side so it can be migrated to any platform. But as suggested by at least 2 contributor it in this post, Spring is cancer contrary to what it claims
spring is a cancer to a project that once it has infected your project you can't do anything without hacking at spring config files ... non-invasive is pretty misleading on that front! – user177800 Mar 11 '13 at 7:18
Claiming that Spring is non-invasive is like claiming that the earth is flat. You completely deny reality based on nothing else than your personal bias.
Spring is not only invasive to your code base, it is also invasive to your brain. It will annoy the hell out of you when you have built a decent confidence in searching the web for information and solutions for your programming problems.
I have done serious programming work in some 10 languages and shells, and almost always managed to find useful information, answers and hints to solve my problems. Usually I manage to find convergence towards a decent solution pretty fast, and sometimes after a bit of digging.
Not so with Spring. A once popular scripting language touted the slogan "there's more than way to do it". For Spring, you will mostly find many ways how not to do it, or many ways that will not work in your particular setup.
I do not doubt that Spring has real value. I do see that. But it comes with way too much magic, that works well as long as it works, but once it fails, the tooling and documentation often fail as well.
I'm working on a 10-year-old Java webapp, and I would like to introduce some new technology into the project. One of the things I would like to start doing is dependency injection. I know the Spring Framework has the capability to do dependency injection, but I am having a hard time integrating the framework into the old project.
Could someone provide an example of what I would have to change in my web.xml, other files I would have to add, and other changes I would need to make? I want the smallest Spring footprint while still being bale to do dependency injection.
There are a lot of examples online about starting a new project using Spring, but I can't find any about integrating Spring into an old project.
Thanks.
You'll have to start by adding a context loader listener into your web.xml, along with the locations of the Spring configuration XML files.
You should configure the Spring DispatcherServlet to accept all URLs that you wish for it to handle.
You should write Controllers to bind and validate HTTP requests, call services, add data to ModelAndView for rendering, and map JSPs to success/failure views as needed.
You should put interfaces in front of your service and persistence tiers. Move implementations into implementation classes that Spring can inject.
Leverage Spring AOP for security and transactions and logging as needed.
Throwing new technology at a project wont make it faster\better, unless you introduce the new technology to all parts of the project. The idea behind DI is to lose dependencies between objects. The project probably is tightly coupled, so you'd have to rewrite at least parts of the thing. Depending on the size, this can be a monster to beat - ask yourself if this is worth it, if it has any positive effect on the project other than introducing new technology.
The reason why there are little to none tutorials about integrating DI container into an old project is quite simple: it usually doesn't make any sense. Either you use the pattern in all places, or none at all. The bastard child that would be creating by mixing both would be a horror to maintain. I'd really advise you think about why you want to introduce a DI container into that 10 year project. Unless there is a real good reason for doing it (and you are happy with rewriting a lot of code) don't do it.
we have a frontend application that that uses Swing. We use Spring framework, but currently it is used just to autowire few beans...
What are reasonable next steps to use Spring more often?
Is it worth for non web application?
What would be advantages and disadvantages?
The advantages of using Spring (or any other dependency-injection) framework, is that you get a (hopefully) loosely coupled system, i.e you classes does not create instances of their collaborators, so you can easily change the implementation.
This is widely known as the Inversion-of-control principle (IoC, also the I in SOLID), and this is a good principle to follow. This means that spring is not limited to web applications, but can be used in any application that want to use an IoC-container (which is basically what spring-core is).
Disadvantages:
This really depends on how you look at things. There is more code (you have to define a entry-point for the injected collaborators), but that also makes the code more testable (the entry-points are seams which you can use to inject mocks and stubs in testing).
Also, you can't look at the code and immediately see which implementation of the collaborators that are used. But that also makes for good code, since you depend on interfaces, not implementations.
You get more config: either in an xml-file (old-style spring), or with annotations. Up until recently you had to rely on non-standard spring annotations to inject (#Autowired) resources, but now you can use the standard java dependency injection annotations, which means that you can switch out spring as your IoC-container without changing your code.
There are probably alot more advantages and disadvantages to using spring in your application, but this should get you started on deciding if using Dependency Inversion is a good thing for your application
More to the point of your question about Swing and Spring. In an application I have been working on we have been using spring to wire up the whole application. The different dialogs get their logic injected (no application logic should (in my opinion) be located together with gui logic). We are using JPA/hibernate as the database-layer, so we use spring spring to create and inject the entitymanager to our DAOs, and set up transactional settings.
I've written swing UI's that are backed by spring.
cons
the startup can be slower but you have to have a large app for that to happen.
and a splashscreen is a good idea in those situations.
its easy to "overbean" or over-zealously make everything a bean, which gets messy.
pros
spring works fine behind a GUI.
it provides a lot of services you can use
the obvious dependency injection and decoupling
a global event system, simpifying some of your own event listeners, for events that will only ever be fired by one source
resource accessing
database access is eays in 2 tier apps
rpc for 3 tier apps is easy
There are other services the spring application context provides, but that I haven't used.
If you go this direction, also look into the java-based configuration for spring, which is new in 3.0. I find that helpful as well, as it makes my spring configuration type-safe.
One disadvantage of using Spring in a Swing application is that Spring DI will make startup slower.
well one would be , if you ever decide to migrate to a web app , all you need ( well almost) to change would be the views. That's the beauty of MVC applications.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.
Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...
Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:
MyProject / src / main / resources / spring /
datasource.xml - My single data source bean.
persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans.
services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans.
controllers.xml - My Spring MVC controllers. Depends on services.xml beans.
views.xml - My view implementations.
This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you.
In my (limited) experience, I've seen this approach yeild the following benefits:
Clearer architecture
Clearly named context files gives those unfamiliar with your project structure a reasonable
place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier.
Helps domain design
If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples:
Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml, or put them in their own transactionPolicy.xml? Talk it over with your team. Should your transaction policy be pluggable?
Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments?
Integration testing
You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans).
Specifically, you can annotate an integration test class as such:
#ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" })
Works well with Spring IDE's Beans Graph
Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph. I've used this before to give new team members a high-level overview of our application's organization.
Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core.
Best practice? If you're using the standard XML config, manage the size of individual files and comment them judiciously. You may think that you and others will perfectly understand your bean definitions, but in practice they're somewhat harder to come back to than plain old java code.
Good luck!
First of all Spring is about modularity and works best if one focuses on writing small components that do one thing and do it well.
If you follow best practices in general like:
Defining an interface rather than abstract classes
Making types immutable
Keep dependencies as few as possible for a single class.
Each class should do one thing and do it well. Big monolithic classes suck, they are hard to test and hard to use.
If your components are small and follow the dogmas above they should be easy to wire up and play with other stuff. The above points are naturally also true of the Spring framework itself.
PS
Dont listen to the points above, they are talking about how to do whatever. Its more important to learn how to think rather than how to do something. Humans can think, repeating something is not clever, thinking is.
I actually quite liked Spring.. It was a fresh breeze of air in your average J2EE Java Beans..
I recommend implementing the example Spring provides:
http://static.springframework.org/docs/Spring-MVC-step-by-step/
Also, I decided to go full monty and added Hibernate to my Spring application ;), because Spring provides excellent support for Hibernate... :)
I do have a DON'T however, which I learned the hard way (product in production)... If you only implement the Controller interface, and return a ModelAndView object with some data as provided with the interface, Spring does garbadge collect those resources, for tries to cache those data. So be careful to put large data in those ModelAndView objects, because they will hog up your server memory for as long as the server is in the air as soon as that page has been viewed...
Start here - I actually think it's among the best Software Dev books that I've read.
Expert Spring MVC And Web Flow
Learn the new Annotation-based configuration for MVC classes. This is part of Spring 2.5. Using Annotation-based classes is going to make writing Unit tests a heck of a lot easier. Also being able to cut down on the amount of XML is a good thing.
Oh yeah Unit Tests - if you're using Spring, you BETTER be Unit Testing. :) Write Unit tests for all of your Web and Service Layer classes.
Read up on Domain Driven Design. The fact that you can use Domain Object classes at all levels of a Spring Application means you're going to have a VERY powerful Domain Model. Leverage it.
However, when using your Domain Object classes for form population, you will want to take heed of the recent security concerns around the Spring Framework. A discussion on the Server Side reveals the way to close the hole in the comments.
A good way to get started is to concentrate on the "Springframework". The Spring portfolio has grown to a big pile of projects around various aspects of Enterprise Software. Stick to the core at the beginning and try to grasp the concepts. Download the latest binaries and check out Spring's petclinic example once you are familiar with the core. It gives quite a good overview of the various projects SpringSource has to offer.
Although the documentation is very good, I'd recommend a book after you grasp the concepts of the core. What I've found problematic with the documentation, is that it's not in depth and can't give you all the details you need.
"...Which technology did you use right away: AOP, complex Hibernate..." - I'd say a better question would be to ask what people did not use right away. I'd add the examples you cite to that list.
Spring MVC and JDBC template would be my starting recommendations. You can go a very long way just with those.
My recommendation would be to follow the Spring architectural recommendations faithfully. Use their layering ideas. Make sure that your web layer is completely detachable from the rest. You do this by letting the web tier interact with the back end only through the service layer.
If you want to reuse that service layer, a good recommendation is to expose it using Spring "contract first" web services. If you start with the XML messages that you pass back and forth, your client and server can be completely decoupled.
The IDE with the best Spring support is IntelliJ. It's worth spending a few bucks.
Whilst its been years since I have used spring, and I can't say I am a fan of it, I know that the App Fuse tool (https://java.net/projects/appfuse/) has been helpful to help people bootstrap in terms of generating all the artifacts you need to get going.
Spring is also very much about unit testing and therefore testability of your classes. That basically means thinking about modularization, separation of concerns, referencing a class through interfaces etc.
If you're just looking to dabble in it a bit and see if you like it, I recommend starting with the DAO layer, using Spring's JDBC and/or Hibernate support. This will expose you to a lot of the core concepts, but do so in a way that is easy to isolate from the rest of your app. This is the route I followed, and it was good warm-up before getting into building a full application with Spring.
With the release of Spring 2.5 and 3.0, I think one of the most important best practices to take advantage of now are the Spring annotations. Annotations for Controllers, Services, and Repositories can save you a ton of time, allow you to focus on the business logic of your app, and can potentially all you to make all of your object plain old Java objects (POJOs).