Adapt standalone application to use Spring - java

I've read about how to use Spring in standalone applications but I'm not sure what should be the approach for refactoring a large code base of 120,000 lines for making the change as gradual as possible.
As far as I understand Spring won't inject anything in an object unless that object is managed by the application context. If this is true, I think I have two choices:
1- Start refactoring from the main class down, but this means complicated scenarios will appear soon.
2- Share the application context statically so that I can start refactoring the simplest things, scalating in difficulty when I'm ready.
I'm not a fan of static access so I would try to avoid that choice, but I don't know if it's a good idea to start with the huge classes that are loaded at startup. Any ideas of the best approach?
By the way, is it OK to inject Swing components until I can fix the dependencies?

I think that before approaching such a big technology change, it may be a good idea to start asking yourself if you are following the architecture that Spring guides you to have when you start using it from the beginning.
Therefore, is your application based on the MVC pattern?
If not, maybe your product is not yet ready for being refactored to
use Spring. In this case, I would suggest refactoring the product
design first, so that it complies with the MVC architectural pattern.
If yes, then I would proceed with a use-case-based approach, starting
from the use cases that required a complicated design and
implementation.
E.g. I would look for very important entity classes or business classes containing a lot of logic. This way, you can reduce the risk of doing a lot of refactoring before realizing that, for example, Spring is not a good fit for the core of your product.
After identifying the most critical use case, you can start to experiment how refactoring works on your current product by introducing Spring from end to end on a single critical scenario (user input - business logic - entity manipulation - persistence). If you are successful, then you keep refactoring, otherwise you can go back and try to understand where you need to change your current product before introducing Spring.
Of course, this works when you have some experience with Spring and you do not have to cope with newcomer's issues. If you are new to Spring, then I would recommend getting some experience with Spring before starting the adventure of refactoring such a big project.

Start simply and wire new code/class with spring. You'll amend your existing main method to initialise the ApplicationContext and load your new feature. Over time then as change requests arrive you'll refactor and migrate the existing codebase to use spring dependency injection.

Related

Manage multiple models in multiple controllers to keep track on them

I was trying to make a simple application in javafx.
I had 8 views (FXML), so one model for each and same for the controllers.
I had to keep the "context" for each model wherever I was... So I had a function setContext which would take a parameter which is a class that regroup every models.
So in every controllers, I had every models.
But a bit latter, I had to had another page, which would take the result of all those page (questionnaire) and show it, so I could have multiple questionnaire... So I was facing the exact same problem, but I didn't want to do it all over again... Because as soon as I'm creating a new questionnaire, I lose the context of the previous one. I also had to add abstractModel and abstractController for stocking every models. It was ratchet.
So I gave up the idea of one controller for each view.
I ended up with a functionnal application, but with one controller which as over 1000 lines... it's only a questionnaire.
I was wondering if there were any possibilities to do what I attempt to do, with multiple controller, but where I don't need to set the "context"? Like... the pages/views auto-save somehow and won't re-instantiate if I'm not asking for it (like a new questionnaire would reset).
Sush as a static class, like a singleton, but for views and which I'm able to instantiate for every questionnaire. But then again, I keep a track on the old ones.
I'm pretty sure it's possible, but can't find anything about it maybe my formulation of the question is just wrong.
Any ideas? Thanks
Your question is bit abstract and it is hard to give a definitive answer. But you might benefit from introducing a dependency injection framework.
One way to do that would be to use Gluon Ignite: "With this library, developers can use popular dependency injection frameworks in their JavaFX applications, including inside their FXML controllers.". You can choose a dependency injection framework you wish from those supported (for example, Dagger, Guice or Spring). With those systems, you can apply scoping rules to your model classes such as Singleton, for those models for which you only wish to have a single instance for your application. You can also use other scoping rules and producers to create models that have different scopes such as within the context of a wizard or created new every time a form is shown, etc.
Beware that using dependency injection frameworks might make your application a little bit more difficult to understand. Anybody maintaining your application has to additionally learn the dependency injection framework. The framework will create objects and inject references to them into your code automatically and your application might be a bit more difficult to debug due to some seemingly magical generated operations that you don't control. Still, it's a tradeoff and, for medium sized applications, the gain in using dependency injection is probably worth it for a lot of apps. From the description you provided, your application may fall into this class, so you should probably seriously consider this approach.
Note that an alternate to a dependency injection system is a service locator (read about it in the Martin Fowler article on dependency injection that I linked earlier). A sample (extremely basic) version of a service locator would be the vista navigator in this small JavaFX navigation framework, though that doesn't pretend to be a full MVC system.
It's just that I can generate multiple questionnaires, which all have the same models and same views and same controllers. But when I create one, it instantiate everything, but it keeps track on all of them so I can edit them later
You could replace your in-memory structure for keeping track of stuff for editing with a persistent storage, for example a JPA based DB access layer or a NoSQL based DB access layer. One advantage of this could also be that the state of the application would be saved if the application is shut down, then restarted, so the user could just pick up where they left off in their questionnaire.

What is the point of dependency injection as used in Spring?

I have been reading the book Spring in Action for a few weeks now to learn about the spring framework. I have about 2 years of programming experience mostly in java with some distractions here and there in Ruby and Python.
After reading the first few chapters, I didn't quite get what the big deal is about dependency injection in spring. I was expecting a AHAAA moment but didn't quite experience that yet. I'm sure I'm missing something important.
Why would I want to wire my beans in xml rather than instantiating them the good old way with the = new myclass();
I understand I can wire beans in the xml via constructor args and properties as well as configure datasources in spring so that I can hide away connection details in an xml file. But why? There is more to this especially when it comes to good software design. Can some one explain the big deal?
Three Words: INVERSION OF CONTROL
In a nutshell:
As soon as you instantaniate "the good old way" you create tight coupling, e.g.: your controller depends on a specific template engine, your entities on a concrete database layer, etc. And that's something you want to prevent and where the dependency injection container (DIC) comes in very handy. It manages your services and you don't really have to care anymore about specific implementations as long as those implement the same interface.
Imagine a simple storage layer class called InMemoryLayer that gets instantiated by you when need it. Now you want to switch it for an awesome new open-source github solution called SuperSecretRemoteCloudLayer. Normally you would now hit "Search and Replace" in your IDE of choice and replace all occurrences of InMemoryLayer with the SuperSecretRemoteCloudLayer. But that's not really handy and quite errorprone, why would you want to do all that hard work by hand? The DIC can do that for you and all you need to take care of, is that both *Layer implement the same interface (so your application won't break).
Spring's big deal is more about dependency injection, not XML-based configuration. As others have noted, Spring has been moving away from XML-based configuration. But DI is core to Spring.
The a-ha is that DI offers a different model for linking components together. Instead of components creating each other directly (and thus being tightly coupled), the components stop doing that, and you inject the linkages from a central location. It turns out that this helps with testing and transaction management in particular.
You don't truly appreciate Spring until you've had to do things the hard way. The hard way being maintaining multiple large projects without a coherent framework. If you have 4 big enterprise wide applications that all have their own way of starting themselves, and managing resources, you're in for a headache. If you know that each application uses spring, then just look for the application context xml! This also makes it incredibly easy to setup a new context for different environments, and test cases, all without mucking up your code base.

How easy would it be to refactor a small JSP/Servlet/JDBC project to SpringMVC/Hibernate

With reference to this post, I am considering starting a new web-based Java project. Since I don't know Spring/Hibernate I was concerned if it's a bad plan to start learning them while creating a new project, especially since it will slow down the early development.
One idea I had was to write a prototype using tech I do know, namely JSP/Servlets/JDBC, since I can get this running much quicker with my current knowledge. I could then throw the whole thing away and start over with Spring, etc, but I'd like to consider how easy it would be to refactor a smallish project from JSP/Servlets/JDB to SpringMVC/Hibernate? My DB could of course be re-used but what about other code... would I expect to save most of it plugged into an MVC framework, or is the paradigm shift big enough this would cause more trouble than it avoids?
Please use the other question for more general advice on choosing technologies
I would advise that you start with Spring and use its JDBC templates and leave Hibernate out of it until you have it working.
Spring will encourage you to use interfaces, which means you'll separate the implementation from the method signatures. You can get everything up and running with Spring and swap out the JDBC DAO for its Hibernate equivalent once you're ready for it.
I can only handle one thing that I'm ignorant of at a time. If you're like that too, follow my advice and start with Spring alone.
+1 to #duffymo's advice. Hibernate is really a whole other beast, and it is especially difficult for folks who are so used to code straight-up SQL to switch to an ORM tool. I mean it took me awhile to be comfortable with Hibernate to do all the work for me, because I just didn't trust it will do a better job than my 'awesome' SQL code. But, as time passes by, I learn to accept that Hibernate is doing a fine job PROVIDED you configured it properly. :)
So, #john, I'll start with JSP + Servlet + Spring first, just like what #duffymo mentioned. Convert your DAO classes to use Spring's JbcTemplate. This forces you to create interfaces for your existing DAO classes. Make sure your DAO classes are stateless, I mean, it should be though. With that, you can easily test the crap out of it in your testcases.
For your servlet to utilize these DAOs, you need to do something like this...
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
SomeDao dao = (SomeDao) ctx.getBean("someDao");
dao.doStuff(..);
The reason for that "tad ugly" code to get the DAO is because Spring cannot wire up the DAO directly into your servlet because Spring doesn't manage your servlet at this point.
Once you get all of this working, you should have some understanding on how Spring's IoC works. Now, you can swap out your servlet and replace it with Spring MVC. I suggest you use Spring MVC 3.x so that you can build your web part the restful way. Trust me, it's whole lot easier and cleaner than Spring MVC 2.x, in my honest opinion.
Okay, when you have JSP + Spring MVC + Spring + JdbcTemplate working, I think it will be a good time to swap your database module from JdbcTemplate to Hibernate. Since you code by interface, it will not cause ripple effects to other modules. PLUS, you can reuse the exact same testcases to test the crap out of your Hibernate DAO classes. Sweeet. :)
... and that's how you end up with JSP + Spring MVC + Spring + Hibernate. :)
Breaking this whole thing down into smaller chunk makes it whole lot easier to learn and digest. At least, when things start breaking in development, you won't indirectly improve your swearing vocabulary, trying to figure out the problems.
I would advice either not using Spring/Hibernate, or using it right away.
Hibernate, but also Spring, influence the modelling of the data and the flow quite a bit. Porting an application from JSP/JDBC to Spring/Hibernate might not always be that easy, especially if you start taking transaction boundaries into account.
My personal advice would be to get a decent Hibernate + Spring book, and start from there.
If you follow good programming practices it will be easy to do the conversion. A servlet could become a controller and a jsp could be re-used as is to become a view. Of course if you are doing things like having business logic in your JSPs it will be more difficult to do the conversion. It will be also good if you already have a data abstraction layer.
This will be an interesting experiment and will help you understand better the advantages of Hibernate and Spring. You may find out that many things these technologies offer, you are doing them already by yourself the hard way.

Looking for design patterns to isolate framework layers from each other

I'm wondering if anyone has any experience in "isolating" framework objects from each other (Spring, Hibernate, Struts). I'm beginning to see design "problems" where an object from one framework gets used in another object from a different framework. My fear is we're creating tightly coupled objects.
For instance, I have an application where we have a DynaActionForm with several attributes...one of which is a POJO generated by the Hibernate Tools. This POJO gets used everywhere...the JSP populates data to it, the Struts Action sends it down to a Service Layer, the DAO will persist it...ack!
Now, imagine that someone decides to do a little refactoring on that POJO...so that means the JSP, Action, Service, DAO all needs to be updated...which is kind of painful...There has got to be a better way?!
There's a book called Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition)...is this worth a look? I don't believe it touches on any specific frameworks, but it looks like it might give some insight on how to properly layer the application...
Thanks!
For instance, I have an application where we have a DynaActionForm with several attributes...one of which is a POJO generated by the Hibernate Tools. This POJO gets used everywhere...the JSP populates data to it, the Struts Action sends it down to a Service Layer, the DAO will persist it...ack!
To me, there is nothing wrong with having Domain Objects as a "transveral" layer in a web application (after all, you want their state to go from the database to the UI and I don't see the need to map them into intermediate structures):
Now, imagine that someone decides to do a little refactoring on that POJO...so that means the JSP, Action, Service, DAO all needs to be updated...which is kind of painful...There has got to be a better way?!
Sure, you could read "Beans" from the database at the DAO layer level, map them into "Domain Objects" at the service layer and map the Domain Objects into "Value Objects" for the presentation layer and you would have very low coupling. But then you'll realize that:
Adding a column in a database usually means adding some information on the view and vice-versa.
Duplication of objects and mappings are extremely painful to do and to maintain.
And you'll forget this idea.
There's a book called Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition)...is this worth a look? I don't believe it touches on any specific frameworks, but it looks like it might give some insight on how to properly layer the application...
This book was a "showcase" of how to implement (over engineered) applications using the whole J2EE stack (with EJB 2.x) and has somehow always been considered as too complicated (too much patterns). On top of that, it is today clearly outdated. So it is interesting but must be taken with a giant grain of salt.
In other words, I wouldn't recommend that book (at least certainly not as state of the art). Instead, have a look at Real World Java EE Patterns - Rethinking Best Practices (see Chapter 3 - Mapping of the Core J2EE patterns into Java EE) and/or the Spring literature if you are not using Java EE.
First, avoid Struts 1. Having to extend a framework class (like DynaActionForm) is one of the reasons this framework is no longer a good choice.
You don't use spring classes in the usual scenarios. Spring is non-invasive - it just wires your objects. You depend on it only if using some interfaces like ApplicationContextAware, or if you are using the hibernate or jdbc extensions. Using these extensions together with hibernate/jdbc completely fine and it is not an undesired coupling.
Update: If you are forced to work with Struts 1 (honestly, try negotiating for Struts 2, Struts 1 is obsolete!), the usual way to go was to create a copy of the Form class, that contained the exact same fields, but did not extend the framework class. There would be a factory method that takes the form class and returns the simple POJO. This is duplication of code, but I've seen it in practice and is not that bad (compared to the use of Struts 1 :) )
I think your problem is not so big as it seems.
Let's imagine, what can you really change in your POJO:
1) name of its class: any IDE with refactoring support will automatically make all necessary changes for you
2) add some field/method: it almost always means adding new functionality what is always should be done manually and carefully. It usually cause to some changes in your service layer, very seldom in DAO, and usually in your view (jsp).
3) change methods implementation: with good design this should cause any changes in other classes.
That's all, imho.
Make a decision about technology for implementing busyness-logic (EJB or Spring) and use its facilities of dependency injection. Using DI will make different parts of your program communicate to each other through interfaces. It should be enough for reaching necessary (small enough) level of coupling.
It's always nice to keep things clear if you can and separate the layers etc. But don't go overboard. I've seen systems where the developers were so intent on strictly adhering to their adopted patterns and practices that they ended up with a system worse than the imaginary one they were trying to avoid.
The art of good design is understanding the good practices and patterns, knowing when and how to apply them, but also knowing when it's appropriate to break or ignore them.
So take a good look at how you can achieve what you are after, read up on the patterns. Then do a trial on a separate proof of concept or a small part of your system to see your ideas in practice. My experience is that only once you actually put some code in place, do you really see the pros and cons of the idea. Once you have done that, you will be able to make an informed decision about what you will or will not introduce.
Finally, it's possible to build a system which does handle all the issues you are concerned about, but be pragmatic - is each goal you are attempting to reach worth the extra code and APIs you will have to introduce to reach it.
I'd say that Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition) addresses EJB 2.0 concerns, some of which would be considered anti-patterns today. Knowledge is never wasted, but I wouldn't make this my first choice.
The problem is that it's impossible to decouple all the layers. Refactoring the POJO means modifying the problem you're solving, so all the layers DO have to be modified. There's no way around that.
Pure decoupling of layers that have no knowledge of each other requires a lot of duplication, translation, and mapping to occur. Don't fall for the idea that loose coupling means this work goes away.
One thing you can do is have a service layer that's expressed in terms of XML requests and responses. It forces you to map the XML to objects on the service side, but it does decouple the UI from the rest.

Is there a simple framework allowing for Dependency Injection in a stand alone program?

We basically need to be able to adjust behaviour at start-up time, by providing desired classes to be produced by various factories inside our application (to avoid the hard binding of the "new" operator).
I am aware that this is provided by several large frameworks, but I was looking for something easily used by a stand-alone Java application without being gigantic.
Any suggestions?
Edit: It is my experience that frameworks tend to grow big as part of maturing (and complex too). I need this to be retrofittable to a legacy application as part of major refactoring (technical debt), so simplicity is essential of the used libraries. I do not mind having to do a bit of coding in our application, but it must be very visible what is going on. AOP has a tendency for moving stuff out of the way, and that may make the application harder to maintain.
Edit: We have now reached the point where we actually need to make a decision. The application will probably live for decades so we need to make a reversible decision with a framework that will be maintained for hopefully as long. I really like the static type check available with Guice, but not that the annotations bind explicitly to Guice instead of being external like in Spring. I also like that code appears to be more concise when using Guice as opposed to Spring. We need something that is robust and helpful. We do not need more than just DI at the moment. Is there a use case that definitive says go for one of these?
Edit 2011-07-27: The final decision was to use the JSR-330 API in code, and choose on a per-project basis if to use Spring, Guice or Weld. For stand-alone applications Guice has worked well so far as the JSR-330 implementation.
You can always use Spring Framework 2.5. It is a big one, but if you planning to use only DI you can use spring-core and spring-beans modules, which are pretty small (ca. 500KB and 300KB).
There is also Google Guice 2.0 which comes with a package with only basic stuff (no AOP) and it's 430KB.
Have you looked at the Google Guice framework? It's pretty lightweight and annotation-based, avoiding XML configuration files
There's also Pico- and Nano-container (from codehaus) which are quite lightweight although the last time I looked (admittedly a few years ago) the documentation was lacking.
I must say that I agree with others about what I assume is your presumption that Spring is massive and confusing. It's really a very simple IoC container and to be recommended.
There are a couple I know of you might find useful:
PicoContainer
Plexus (used in Maven)
I've found Plexus very useful in standalone apps as it has optional utility components for CLI interaction.
By "gigantic" I'm going to assume you're referring to Spring, but that's unfair, since you can cherry-pick the bits of Spring you want to use. If all you need is the IoC container, just use the appropriate JAR files and the appropriate bit of the API, and ignore the rest of it.
Most answers so far seem to be concerned with the size of the jar files to be added.
However I think the more important question is the impact on the project: How many lines of code must be added/changed in order to use the framework?
Even the "big" spring framework is actually very easy to use:
You basically need:
a xml file that describes your factories.
one line of code to initialize the container by loading the xml file
The nice thing is that spring is non-intrusive. So you do not have to implement specific interfaces or add any specific annotations or imports to your classes.
At best the single spot where you actually initialize the Spring container is the only
place in your application that has an actual dependency to spring classes.
I would strongly suggest to take a look at Spring ME. Although originally meant to be a way to use Spring on Java ME applications, it also works fine for standalone applications.
True, it doesn't give you all of the bells and whistles that Spring (Full) has to offer, but then again, Full Spring is much much more than a simple dependency injection framework.
On the plus side: it's based on a (compliant) subset of Spring's configuration files, and the footprint of the runtime is 0%. In fact, there isn't any. Spring ME will take your application context, and turn it into a class that has no dependencies on classes other than your own.
What's wrong with Spring?
These days it's packaged pretty well so you wouldn't need to take the whole kit and caboodle.
As an aside, I'm not a fan of the annotation based injection frameworks. This is because the annotations are bound to the class rather than the instance, the later being a pre-requisite, imho, for DI. This means every instance of a given class gets the same object(s) injected, which seems to defeat the point.
Also consider that DI doesn't even need a framework, what's wrong with your main method wiring together the application?
If you want something maximally simple and appropriate, then write some code that does what you want done. Presumably this involves wiring together factories based partly on fixed logic, and partly on run-time settings.
This has the advantage that the set of possible run-time configurations is known, and so documentable and testable.
It has the disadvantage that an deploying an unanticipated logic change inherently takes an extra second or so of compile time, and (more significantly) can't be sneaked into production without full testing by disguising it as 'just a configuration change'.
About a year ago I asked myself a question very like this. So I spend a few hours reading the Spring and Guice documentation. After about an hour with Spring I was left feeling that I could get a basic web app going, but had no idea how to use it in a stand alone application. After an hour with the Guice document everything had clicked and I could see just how I to do what I wanted to get done.
Now on to recommending Guice? Well no. What does your team already know? If someone already knows say Spring leaver that knowledge and have them spread it about. Like wise with Guice or Pico.
If you want something really light weight you might want to have a look at fuse it's fairly extendable so might be what you're looking for.
cheers
N

Categories