Does it make sense to combine Spring with JSF? [duplicate] - spring

I'm a little confused by the mixed use of JSF2+Spring+EJB3 or any combination of those. I know one of the Spring principal characteristics is dependency injection, but with JSF managed beans I can use #ManagedBean and #ManagedProperty anotations and I get dependency injection functionality. With EJB3 I'm even more confused about when to use it along with JSF or if there is even a reason to use it.
So, in what kind of situation would it be a good idea to use Spring+JSF2 or EJB3+JSF2?
Until now I have created just some small web applications using only JSF2 and never needed to use Spring or EJB3. However, I'm seeing in a lot of places that people are working with all this stuff together.

First of all, Spring and EJB(+JTA) are competing technologies and usually not to be used together in the same application. Choose the one or the other. Spring or EJB(+JTA). I won't tell you which to choose, I will only tell you a bit of history and the facts so that you can easier make the decision.
Main problem they're trying to solve is providing a business service layer API with automatic transaction management. Imagine that you need to fire multiple SQL queries to perform a single business task (e.g. placing an order), and one of them failed, then you would of course like that everything is rolled back, so that the DB is kept in the same state as it was before, as if completely nothing happened. If you didn't make use of transactions, then the DB would be left in an invalid state because the first bunch of the queries actually succeeded.
If you're familiar with basic JDBC, then you should know that this can be achieved by turning off autocommit on the connection, then firing those queries in sequence, then performing commit() in the very same try in whose catch (SQLException) a rollback() is performed. This is however quite tedious to implement everytime.
With Spring and EJB(+JTA), a single (stateless) business service method call counts by default transparently as a single full transaction. This way you don't need to worry about transaction management at all. You do not need to manually create EntityManagerFactory, nor explicitly call em.getTransaction().begin() and such as you would do when you're tight-coupling business service logic into a JSF backing bean class and/or are using RESOURCE_LOCAL instead of JTA in JPA. You could for example have just the following EJB class utilizing JPA:
#Stateless
public class OrderService {
#PersistenceContext
private EntityManager em;
#EJB
private ProductService productService;
public void placeOrder(Order newOrder) {
for (Product orderedproduct : newOrder.getProducts()) {
productService.updateQuantity(orderedproduct);
}
em.persist(newOrder);
}
}
If you have a #EJB private OrderService orderService; in your JSF backing bean and invoke the orderService.placeOrder(newOrder); in the action method, then a single full transaction will be performed. If for example one of the updateQuantity() calls or the persist() call failed with an exception, then it will rollback any so far executed updateQuantity() calls, and leave the DB in a clean and crisp state. Of course, you could catch that exception in your JSF backing bean and display a faces message or so.
Noted should be that "Spring" is a quite large framework which not only competes EJB, but also CDI and JPA. Previously, during the dark J2EE ages, when EJB 2.x was extremely terrible to implement (the above EJB 3.x OrderService example would in EJB 2.x require at least 5 times more code and some XML code). Spring offered a much better alternative which required less Java code (but still many XML code). J2EE/EJB2 learned the lessons from Spring and came with Java EE 5 which offers new EJB3 API which is even more slick than Spring and required no XML at all.
Spring also offers IoC/DI (inversion of control; dependency injection) out the box. This was during the J2EE era configured by XML which can go quite overboard. Nowadays Spring also uses annotations, but still some XML is required. Since Java EE 6, after having learned the lessons from Spring, CDI is offered out the box to provide the same DI functionality, but then without any need for XML. With Spring DI #Component/#Autowired and CDI #Named/#Inject you can achieve the same as JSF does with #ManagedBean/#ManagedProperty, but Spring DI and CDI offers many more advantages around it: you can for example write interceptors to pre-process or post-process managed bean creation/destroy or a managed bean method call, you can create custom scopes, producers and consumers, you can inject an instance of narrower scope in an instance of broader scope, etc.
Spring also offers MVC which essentially competes JSF. It makes no sense to mix JSF with Spring MVC. Further Spring also offers Data which is essentially an extra abstraction layer over JPA, further minimizing DAO boilerplate (but which essentially doesn't represent the business service layer as whole).
See also:
What exactly is Java EE?
JSF Controller, Service and DAO
#Stateless beans versus #Stateful beans

There's no real easy answer here as Spring is many things.
On a really high level, Spring competes with Java EE, meaning you would use either one of them as a full stack framework.
On a finer grained level, the Spring IoC container and Spring Beans compete with the combination of CDI & EJB in Java EE.
As for the web layer, Spring MVC competes with JSF. Some Spring xyzTemplate competes with the JPA interfaces (both can use eg Hibernate as the implementation of those).
It's possible to mix and match; eg use CDI & EJB beans with Spring MVC, OR use Spring Beans with JSF.
You will normally not use 2 directly competing techs together. Spring beans + CDI + EJB in the same app, or Spring MVC + JSF is silly.

Related

No "new" objects for Java Spring and how to convert legacy application to "Spring" concept

I have just started learning Java Spring and the concept of Dependency Injection (DI) and Inversion of Control (IoC).
I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
The container manages the dependencies between classes and the lifecycle/scope of the object.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?
I learned that all objects whether it is singleton, prototype or request and sessions, are all retrieved from the container.
That is not quite right. Not all objects, but those you have the cotainer told to resolve, are retrieved from the container. In general you use the #Component annotation to mark which of your objects should the container know of. Besides #Component there are other annotations which do in principle the same, but allow a more finegrained semantics, e.g. #Repository annotation, which is at its base #Component and put #Target, #Retention, #Documented on top.
The container manages the dependencies between classes and the lifecycle/scope of the object.
Yes. The container does the wiring up for you, i.e. resolving dependencies annotated with #Ressource, #Autowired or #Inject depending on which annotation you prefer.
During the lifecycle there are possible events, which allow usage of lifecycle callbacks.
Also: You could determine the bean scope.
The fundamental idea behind this is there are no "new" operators for application using Spring Framework as the backbone of the system. (Please correct me if I am wrong).
The fundamental principle is, that you delegate the creation of objects of a certain kind to the container. Separation of creation and consumption of objects allows greater flexibility and in consequence better testability of your application.
Besides the "components" of your application, there are e.g. the typical containers like ArrayList or HashMap, upon which you use the new-operator as before.
I wanted to modernize legacy applications coded without the Spring framework and manages the 3rd party libraries classes and injects them using Spring.
How should I approach this?
From what was said above, it should be "simple":
1) Go through each class file and look for its dependencies
2) Refactor those out and put #Component on top of the class
Special case: 3rd party objects, where you do not have access to the source. Then you have to wrap its construction yourself into a factory e.g. with #Bean.
3) Add the missing dependencies via #Autowired (the spring specific annotation for marking dependencies)
4) Refactor components of the service layer with #Service annotationinstead of #Component.
5) Refactor the data access layer, instead of using #Component, you can use #Repository.
This should give you a base to work with.

Transitioning to Spring Data

We are currently using Spring 3.2.3 + JPA (Hibernate). We use aspects for transaction support as opposed to annotations. We write out own entity services (read: repositories) to abstract the persistence away from our application.
I've read a lot about Spring Data and feel it would make our code considerably cleaner and more robust. I wonder though, are there any gotchas that I should consider before transitioning?
Thanks
If you're already on JPA the transition should be as easy as it can be: activate the repositories, point the infrastructure to your EntityManagerFactoryBean and off you go.
Transactions should just work fine as well. The annotation based usage within Spring Data is selectively activated for the repository beans only. They are configured to take part in existing transactions by default, so any custom larger scoped transaction setting should be in effect already.

Spring Data JPA like project not dependent on Spring

Does anyone know any Java frameworks that follows the repository approach with automatic implementation of query methods (e.g. findByNameAndLastName(…)) but not tied to Spring, only pure JPA. Such feature also exists in GORM. I would like to see if there is any project that can be used in Guice or pure JavaEE environment without bringing Spring as a dependency.
(Disclaimer: I am the author of Spring Data JPA)
There is the CDI Query Module which is very similar to what Spring Data JPA. There's also a DeltaSpike module.
Note that Spring Data JPA ships with a CDI extension that creates repository proxies as plain CDI beans and does not bootstrap a Spring container. There are APIs that allow the creationg of repository proxies programmatically such as:
EntityManager em = // … obtain EntityManager
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
UserRepository repository = factory.getRepository(UserRepository.class);
Yes, it still requires Spring libraries to be present on the classpath but it is then using them similar to how you would use Commons Collection or the like. We try not to reinvent the wheel and the Spring libraries we depend on provide a lot of useful code that we do not have to re-code.
So if it's Spring as DI container you're worrying about, feel free to give the CDI extension of Spring Data JPA a choice. If you don't want to use any Spring whatsoever (for whatever reason), have a look at the alternatives.
Based on Oliver's information, followed up as also interested in this topic --
CDI Query joining Deltaspike mail thread: http://apache-deltaspike-incubator-discussions.2316169.n4.nabble.com/Porting-the-CDI-Query-extension-project-to-DeltaSpike-td4329922.html
Deltaspike base link: http://deltaspike.apache.org/index.html
Getting started: http://deltaspike.apache.org/documentation.html
Just did their 0.4th release as of 5/31/2013.
However, have not done enough of a review to contrast/compare Deltaspike versus Spring-Data w/ CDI extensions (spring-data being very mature).
Take a look at Tomato on github!
It is a functional replacement for Spring JPA, has zero dependencies, performs better and is far easier to use. It will reduce your data access code by 98% and deliver the results you want right out of the box.
https://rpbarbati.github.io/Tomato.
If you want free, fully functional dynamic forms and/or tables for any Tomato entity or hierarchy, that can also be customized easily, try the angular based companion project...
https://rpbarbati.github.io/Basil
Both are current, maintained projects.
Try it yourself, or contact the author at rodney.barbati#gmail.com with questions.

Spring transaction support in Netty handlers

I am using the following versions:
Spring 3.1.1.RELEASE
Netty 3.4.0.Final
Hibernate 3.5.6-Final
Now, I have a Netty server that works fairly well - the root of the server, the pipeline factories and the base "stub" of the server that owns everything are all set up with Spring. In this stub, spring #Transactional annotations work just fine.
However, in the handlers, which are stateful and created dynamically depending on what state the user is in - #Transactional doesn't work. I'm fairly sure I understand why. I even have a "solution" - but it's not very good.
After the decoders and encoders, I add an ExecutionHandler:
pipeline.addLast("execution", new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16,1000000, 1000000)));
This appears to be where the Spring transaction support is breaking. Since Spring is unaware of these threads, it can't bind any transactions to them. The classes are proxied correctly, but in debug they have no associated transactions.
My solution is crappy, and it needs to be replaced by a real solution:
Session sess = SessionFactoryUtils.getSession(getSessionFactory(), true);
That's bad because it relies on me to release the session, and it may not even be transactional, I haven't checked. It sucks in a lot of ways.
Anyway - the root of the question. Given the above tech, what's my path to getting my #Transactional notations working on the Netty handlers?
Write an ExecutionHandler that's Spring aware?
NOTE: I can't upgrade to Hibernate 4, due to lack of compatibility with Spring-Flex, used in another project in the group. Probably the same story for the Spring version, can't remember.
I suggest you create these netty's handler inside spring container and inject the service or persistence layer into the handlers so you can have these layers independence from netty and of course these are old school spring beans.

GWT Spring Integration - How to do AOP logging?

I have a GWT application where its RPC services are handled by a GWTHandler bean so that it can integrate with Spring smoothly. The application works. No problem with that.
My issue is I can't do any AOP logging with Spring. I like to log user activities from the GWT interface using AOP. (I could of course do it the old way of calling an RPC service for every action that a user does and log those action, but that is not the AOP way). I have to do it in AOP because that's the client's requirements.
I tried using the normal Spring AOP with a generic pointcut pattern "execution(* .(..))". It's able to capture all methods except for the GWT services. So in other words, it's useless. I could of course log the backend Spring DAO's using AOP but how do I know which RPC service it came from? These DAO's are used by numerous classes and methods (not exclusive to GWT).
I tried exploring GWT-ENT package. It looks good. However, it works on the client's side and your classes must implement Aspectable. This means requiring changes on all client classes on my GWT application. Furthermore, you can't use private methods since to handle AOP with GWT-ENT, you need to create your classes via GWT.create instead of the new(). Having private methods throws an error. I set-up a simple application and really private methods don't work.
I tried searching the GWT-SL package (where my GWTHandler came from). They mentioned about something about AOP, but the info is very scarce. Google didn't give me any solutions or examples.
I've tried everything I could think of and searched Google with all my efforts but I can't find a solution to my problem.
All I want to do is log methods from my GWT services via AOP. Let's say a client goes to the Report tab. Then he click on Delete button record. I want to log that activity via AOP.
I'm using GWT (with SmartGWT) and Spring/Hibernate stack.
Spring AOP will only advise public methods of beans in your Spring context, so GWT infrastructure is out unless you specifically instantiate it through the Spring container.
You could use compile-time weaving with AspectJ to wire your AOP into everything, but it might get a bit messy. It's also uncertain that it would work, unless you are compiling the GWT classes in question.
I'm gonna answer my question.
Instead of performing AOP logging on the GWT server implementations (which theoretically should work but in practice it's not), I decided to do AOP logging on the DAO layer. Just make sure you log the DAO not the Hibernate Session

Resources