Scope confusion regarding session beans, proxies, and singletons in a Spring 3 managed JSF app - spring

This seems like it's basic Spring 101 stuff, but I can't seem to find the correct way to do this. The situation is as follows; in my web app there is a single entry point which is a controller that handles users coming from an outside system. The transfer is just a POST request with a bunch of associated information pertaining to that user. Apon entry, I need to create a new User bean and load it with that users information. Additionally, when the user hits a view which triggers some service, I need for that service to be able to access the appropriate User bean instance.
The first way to do this that came to mind was to have a UserManager service which would create a new instance of User, fill it w/ data, and then register it in the Spring container with the username as the bean name. Then when a service is invoked, the service would do something like Factory.getBean(username) to find the appropriate User instance. The problem I see here is that I'm losing the link between the user & which User bean belongs to them. Additionally, I'd like to avoid having the user carry the bean around in the session if at all possible. Is this where I am supposed to be using Spring AOP & proxies?
What is the typical Spring pattern for solving this type of situation?

So it is now many weeks later (since asking this question), and consequently my knowledge level has been expanding exponentially, so I figured I might as well answer my question for anyone who might find it helpful (not to mention the question wasn't very clear to begin with).
The basic answer is: use proxies. Since a singleton is only instantiate 1 time, you cant inject another class which has a shorter lifespan, eg. session scope. For those requiring more information, checkout stateful vs stateless beans. More or less what I ended up doing is this... the services contain STATELESS code for manipulating data (think verbs; RegisterUserSvc, AddPartSvc, etc). The data which these services manipulate is stateful. For instance, each user has a own copy of their own data object, lets say TodoListBean, which is in a different state for each user.
So how does a service, AddTodoItemService for instance, manipulate this data? This is where the proxy comes into play. When instantiated, the AddTodoItemService gets injected with a proxy for the TodoListBean, instead of the actual object. That way when the service needs to access the TodoListBean the container will serve up the a TodoListBean out of the current users session, and therefore the service will be operating on the correct bean (based on which user invoked the service), instead of doing something silly like having numerous copies of the service included in each users session scope.

Related

Using correctly the #Scope annotation is Spring 3 web application

I recently readed carefully about the spring mvc 3 beans scope, specifically the web ones(session, request and global session) and i have some doubdts:
If i have a controller, why should i annotate him with other scope aside of singleton? I mean, the controllers are supossed to handle the requests and instantiate the view resources of all the app, so why give them a, for instance, session scope? what is the advantage of do that?
Is advisable making the services layer session scoped?
And finally, is there any convention or good practices that dictates where and when is more convenient the use each one of the web scopes? If there is, can somebody provides me the link or information about it? Not necessary convention or good practices, also your experience about it.
Thanks very much.
I mean, the controllers are supossed to handle the requests and
instantiate the view resources of all the app, so why give them a, for
instance, session scope?
In an average web application, you have various objects that exist on a per-session basis. Example can be user profile, or some kind of cabinet, or wallet, etc.
To be able to use those objects in service, every time you should get from session, and pass through the service chain. Instead of doing this, of course it is better to have those available in your service, without a need to pass it explicitly.
Really good example (in practice) you can find here.
An ideal practical example of request scope bean is HttpServletRequest, which should be unique obviously for each request, therefore it is request scoped and created for each request.
From my experience, without any explicit need for a case, you don't need to bother yourself with changing scopes. It is not without reason that default scope is Singleton, it is by purpose - because in most of the applications and basic scenarios you need beans as singleton. However as your main concern was with Session and Request scopes, the above examples are cases which you need often in web application.

Single instance of an object per transaction

I have a use case, that theoretically seems to me as it would be a solved problem. But i'm not able to find a sure fired implementation.
I've created a RESTful API, using Apache CXF, Spring and Hibernate
This application encompasses a standard Service-Proxy-DAO layered structure
I need to instantiate a custom logger object at my service (or pre-service) layer and initialize a bunch of parameters which will remain constant, for the most part through every call that goes through my application layers and back.
How can i, for every individual service call, initialize this logger object once, and use it across all my layers without having to instantiate it everytime. Either i inject the initialized object in every class i need or something on those lines.
I don't want to use static blocks, or pass the object in method signatures.
Is there anything that i can use as a part of the Spring, CXF or other java framework that allows me to implement this use-case.
EDIT: I would define a transaction as a single call to a web service endpoint, from invocation to response.
ThreadLocal would be an ideal candidate to solve your problem.
UPDATE:
Creating a thread local that is available in all the places where this "shared" reference is required will give all these contexts access to this resource without having to pass the reference around.
see http://www.appneta.com/blog/introduction-to-javas-threadlocal-storage/ - looks like a good explanation of how to use thread local and also deals with your problem space.

Using ServiceLocatorFactoryBean of Spring

I am creating third part login system for my web application using Oauth2 and have to support various third party Oauth2.0 service provider like
Gmail
Facebook
MSN
Yahoo
Twitter
I have already working code for these.Each service provider have a certain set of configuration which need to be created before starting Oauth process.I was thinking about using ServiceLocatorFactoryBean of Spring and create few services for each Oauth provider and based on what user has selected can fetch that specific service.
Is my approach is good enough or is it like a overuse / overcomplicated one
Edit
As per one answer, We can create a single bean with singleton scope and inject Map of required services to it so as we can fetch services from Map based on what user has selected, though approach is fine but won't that force us to load every services in Memory and no matter if we will use them or not, they will remain in Memory
Using ServiceLocatorFactoryBean is a way to do it and solves the problem of getting a bean (implementing an interface) based on a String key lookup.
The javadoc says that the class is meant mostly for injecting prototype scoped beans, but also works for other scopes altough they don't advise it.
The javadoc gives an indication that is not the use case for which the ServiceLocatorFactoryBean was created, another solution that gives the same work is to just create a singleton bean OAuthServiceProvider that returns the correct service depending on a string using just some if/elses or a map.
In the long run it would more readable, the use of the ServiceLocatorFactoryBean seems not to buy us much compared to that.

Centralising logging using Spring AOP

I was hoping that you guys will be able to help me with a conundrum that I am currently facing.I am currently working on an existing web application project where one of the requirements is that we have to centralise logging. The application is a layered application consisting of the client layer (i.e. the views), service layer, business layer and DAO layer.
Currently, logging in the application is handled by controller methods where each controller method that needs to have some information logged, manually logs the data by calling a logging function. Requests handled by these controller methods come from many different client sources including mobile devices (such as phones), web browsers, web services etc. Currently, all the data that needs to be logged is captured in a general purpose object which is passed to a logging method to persist these properties to a DB table.
The problem is that this general purpose object is exactly that, a general purpose object. Its used for many other tasks including logging, searching and many other tasks. When this general purpose object is used for logging, with the exception of a couple of attributes, most of the the attributes which are used to populate the general purpose object (in the case of logging) come from the request i.e. (a HttpServletRequest object). As a result of the versatility of this object, there is a potential for this general purpose object to get misused. Hence, we want to get rid of this general purpose object and create specialised objects for specialised tasks.In the case of logging, we have decided to create a logging object that we will use persist the data we need to have logged. We will be using Spring AOP effect the logging
The conundrum is this
1)Should we be using the controller to set the properties on the new specialised logging object that we want to log and then using an AOP advice, retrieve the log object for persistence once a controller method has finished executing
OR
2)should we set the properties on the new log object in an AOP advice using attributes that we have placed in a request object (i.e. HttpServletRequest object)?
My issue with option 1 is that the controller becomes aware of the logging and also, according to good design principles, a controller is only supposed to delegate tasks to business and services layers to perform such tasks. Option 1 will mean that the controller is doing more than just delegating tasks i.e. it will be building log objects
My issue with option 2 is that it couples my logging object closely with the request object (i.e. HttpServletRequest object) and hence I am wondering whether there are any potential with that approach.
Any sort of suggestions, advice and critique will be welcome. Also, if anyone has had to deal with a similar situation, I want to hear how they went about addressing the issue.
Thank you all in advance.
I'd add logging to the service layer, expressed as interfaces, using aspects.
You can use HTTP filters or aspects to log from the controller layer.
You can apply AOP in multiple layers as needed.

How to share bean INSTANCE across war in SPRING?

I want to share a singleton bean across multiple war. I know sharing ApplicaitonContext using parentContextKey attribute(Example, http://blog.springsource.org/2007/06/11/using-a-shared-parent-application-context-in-a-multi-war-spring-application/)
But this way instance of bean created multiple (for 2 war, 2 instance). I want only 1 instance across 2 war.
Another way, If i set some value in any POJO, it should be accessible in another war.
Reason i need this is, there are some beans(like HibernateSessionFactory, Datasource etc which are expensive) which are created multiple times(n instance for n war). Whereas i want to utilize same instance instead of creating same in different war.
Can anyone provide me solution for this?
You could achieve this by binding the objects into the global JNDI tree. That means that both WARs would have references to an object looked up in JNDI.
Hibernate allows you to use the hibernate.session_factory_name property (this may well be a good starting point. Data sources should already be looked up from JNDI.
One thing, I would not class a session factory or a data source as expensive, so you may well be saving a miniscule amount of memory in exchange for a lot of additional complexity, so I would ask myself the question on whether this is worth the additional maintenance headaches.
Spring provide a way to expose any bean (service) and these bean can be access from any other web application or any standalone application.
please refer Remoting and Web Service using Spring to get more details.

Resources