Tomcat Spring WebApplicationContext - spring

In the Spring framework reference I found this:
The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean method at all, and thus no dependency on Spring APIs at all.
but I have no idea to realize this.
After a lot of search I found this
avoid to use getBean in your application code, try to write a single class with one or more getBean() calls, this bootstrap class must be executed at the startup of your webapplication
is this a more recommended way?

Spring encourages you to use Inversion of Control, where the framework (e.g. Spring) injects dependencies into your objects, rather than your objects fetching things from the framework.

Related

When providing a Spring RestController as a part of a library, how should I make dependencies be injected?

I'm providing a Spring RestController as a part of a library. Currently I have reusable jaxrs services, but I need to make Spring Boot alternatives. One RestController for example has 2 dependencies: one is a service that I could see being a bean and the other a String property.
I'm wondering what is the idiomatic way to expect to get those dependencies from users consuming the library. I had a few ideas about how it might happen, but wasn't sure what was the right or at least best practice way to do it.
Should users construct the RestController manually using the constructor (not using dependency injection)? I actually couldn't even figure out how to do this such that the Spring Boot Application knew about it and didn't see it in guides, so I was assuming this isn't the normal way to provide RestControllers. I only wondered if this was the right way to go as dependency injection being used for a third party library class's dependencies seems like it could be hard to manage.
Should both be beans, with the String property being a named bean? I have this one working, but I'm wondering if consumers of the library having to provide beans that the library's RestController expects is tricky or a bad practice.
Should the simple service be a bean and the String injected via #Value?
Is there some alternative or better way?

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.

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

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.

How do I get one common instance of ApplicationContext using Spring in Java

I know that Spring is most useful for dependency injection. But what I don't understand is how do I have one common "ApplicationContext ac=....." for the whole project, lets say I have a WebApplication and it has multiple number of packages but all of them still in one project , so how do I make the ApplicationContext instantiate only once. I had read somewhere that in Spring objects are initialized only once something as singleton beans but what I dont understand is that how is it different than Singleton design pattern, there is one question on this in SO but I couldn't quite clearly understand the answer as I am a newbie to Spring trying to learn by myself. Any help would really be appreciated. Sorry if the Q is too long. Hope I was able to explain my doubt clearly.
Spring veans are by default Singleton, although it is possible to configure them as prototype which means that a new bean will be created upon each request. In practice, singleton means one instance per context and are their lifecycle is managed by Spring nwhich also provides hooks into the various stages. Spring does not manage prototype beans once they have been created.
It is common in a SpringMVC application to have more than one context (one for the business services, the other for the web controllers). You would only need to create an ApplicationContext when building a standalone application. SpringMVC applications use the ContextLoaderListener to create the necessary contexts.

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