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.
Related
My Spring Boot Application features a content management system. I would like to be able to dynamically load new components without requiring an application restart. An example component may be loading a new video player component or ad component. Each component would likely contain its own controllers and views.
What would the recommended pattern be for this, and what is a good framework to help handle this? Is OSGi an option?
I'm afraid there isn't a 100% solution. There's maybe some options; let me highlight the following three:
There are Spring factories, a way to (auto-)configure your beans.
Another interesting approach to go is the way of how Spring Boot handles extensions by itself - by having its own spring-boot-starters, like in this article: https://blog.codecentric.de/en/2014/11/extending-spring-boot-five-steps-writing-spring-boot-starter/, combined with Spring Factories you could
The most plugin-like solution is the spring-plugin-project. However it looks like only loading is supported, some other features like versioning are missing, too. So you probably have to build it by yourself.
So the main problem might be in unloading and updating these things at runtime, which leads me to the final observation:
In general I have the impression that the concept of having a plugin is working a bit against the idea of Spring Boot, as it is designed for microservice architectures. So the added (plugin) functionality probably would rather be a separate microservice (with its own storage) which gets orchestrated by a gateway, here let me highlight the spring-boot-based JHipster project to show the idea of such an architecture.
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.
I'm currently rebuilding an existing PHP application using Java. I therefore have an existing frontend GUI and an existing database schema that I'm working with.
Here is the technology stack I'm working towards:
jQuery, client-side
Wicket, front-end
Spring, ???
Hibernate, ORM
MySQL, database
Before reading about Spring in both Wicket In Action and the Hibernate documentation, I envisioned wiring the two together through my own business logic. I have experience with JBoss Seam, but am told that Spring is hardly comparable (although the documentation suggests otherwise, IMO). Short of adding a book about Spring to my reading list (I haven't found an appropriate one with good reviews yet), I'm at a loss.
What benefit(s) will Spring provide in this technology stack?
Subjective & optional follow up question: what reference material (book, website, etc) will get me started with the portion of Spring 3 I may utilize?
First, you can make your web application without Spring. But Spring will greatly facilitate things. Spring framework is a lightweight, non-invasive. Spring is like a kind of conductor. Among other things Spring helps you in:
To keep your objects loosely coupled. This will make your application more flexible and open to future changes
Powerful support for transactions through the AOP (Aspect Oriented Programming).
Object-relational mapping (ORM) integration module. Spring doesn’t attempt to implement its own ORM solution, but does provide hooks into several popular ORM frameworks, including Hibernate, Java Persistence API, Java Data Objects, and iBATIS SQL Maps. Spring’s Transaction management supports each of these ORM frameworks as well as JDBC.
The Spring MVC framework. Even though Spring integrates with several popular MVC frameworks, it also comes with its own very capable MVC framework that promotes Spring’s loosely coupled techniques in the web layer of an application.
A good book about Spring: Pro Spring
Spring, as noted in this review is non-invasive. It just wires your application components. And provides useful classes that make using other frameworks easier (JMS, JPA, etc). Spring doesn't force you to use its classes or interfaces anywhere.
What it handles is the creation of your components (objects), so that you can refer to a class' dependencies, without instantiating them. I.e. you say what your class needs, not how it is obtaining it. This makes the application very flexible.
That's in short - for more, read the linked article. It's not about the latest version, but that doesn't matter.
In addition to dependency injection, Spring offers features like declarative transaction management, simple integration with ORM, aspect-oriented programming support and many other nice things.
For documentation see Spring reference: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html
#Dolph, in the simplest term, think of Spring as your application framework at the highest degree. This "framework" provides several "component buckets" where you can easily plug in different types of implementations. For example, for ORM, you may choose to use Hibernate over JPA or TopLink, for front end, you may choose Wicket over Struts or SpringMVC, and so forth.
The whole beauty of this (besides all the goodies stated in other posts) is it allows you easily swap out any of these implementations easily in the future. So, you can essentially rip out Hibernate one day and replace with TopLink, and it will never cause ripple effect to other components.
Another beauty of using Spring is your code becomes less clutter and has loose dependencies with other classes because you spend less time creating new objects yourself, Spring handles that for you. That said, you will quickly realize how easy for you to test your code because your API to be tested becomes very atomic. This is one primary reason why folks get discouraged in writing testcases, because they quickly realize that in order for them to test one API, they have to construct whole lot of things just to test that. Because of that, the whole process is brittle, imagine if you change that API, you need to reconstruct everything before testing it again.
Pro Spring book is good, mentioned by #JLBarros. I like Spring in Action very much. It is very very easy to read when I first got started with Spring. This is probably one reference book that I read from skin to skin.
I am modifying existing java web application that was written long time ago, and it is written in the wrost possible way. It has business logic and sql statemens in JSP files.
Because of the certain constraint, I can not re-design the entire application. but I can implement better design in any new feature that I add.
can anybody suggest me any MVC framework that I could easily integrate in existing app. I need to have framework that is not depended on many external jar files and it does not cause any issues with existing application.
I am modifying existing java web
application that was written long time
ago, and it is written in the wrost
possible way. It has business logic
and sql statemens in JSP files.
Sounds like a good candidate for being thrown away to me.
Because of the certain constraint, I
can not re-design the entire
application. but I can implement
better design in any new feature that
I add.
The entire app needs to be re-designed, but you can't redesign the entire app. It's contradictory.
can anybody suggest me any MVC
framework that I could easily
integrate in existing app. I need to
have framework that is not depended on
many external jar files and it does
not cause any issues with existing
application.
You can't help but cause issues with the existing application, and there will be external JAR dependencies if you use a framework. I'd still recommend it, because a framework will give you a lift that will be worth the extra JARs. Your WAR file will be bigger - so what? Disk space is cheap.
Sounds to me like MVC is the least of your problems. You should be concentrating on the idea of a properly layered application first. If you had well-defined persistence and service tiers you might have a chance.
Think about the problem without worrying about the UI for now. Start with the persistence tier. Get a DAO and model objects going. Then move onto the service tier: transactions, units of work, and use cases implemented using the DAO and model objects. Unit test both layers thoroughly.
Once you have those you're free to concentrate on making the view tier work properly. It'll be easier letting the controllers interact with services. Your UI can be HTML, CSS and JavaScript or Flex. All the logic will be out of the view and into the back end where it belongs.
Don't be afraid of JAR dependencies. It could steer you away from something that will help you. I'd recommend Spring first and foremost. It'll help with all your layering issues. Its web MVC is as good as there is, too.
If you can't re-design the whole application and are concerned about the weight of the framework, then I suggest not adding a framework. You'll end up with a Frankenstein build where the application is inconsistent, and not a lot of benefit.
Instead, why not roll your own? When you add new features (or revise existing ones), you don't have to cram everything into a jsp. Create your own data access layer, and your own business object, and link those to each other and to the UI in your jsps appropriately.
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).