Custom spring scopes? - java

Anyone know of any other custom spring scopes than Servlet Context Scope and ThreadScope ?
If you've made some closed-source custom scope I'd really also be interested in hearing what it does and how it worked out for you. (I'd imagine someone would make a WindowScope in a desktop app ?)
I'm open to all use cases, I'm looking to expand my horizon here.

We implemented our own custom Spring scope. A lot of our code works at a relatively low level, close to the database, and we maintain a conceptual level on top of that with its own object model of data sources, links, attributes etc.
Anyway, a lot of beans require a so-called StorageDictionary (an encapsulation of this object graph) to do their work. When we make non-trivial changes to the object graph, the dictionary sometimes needs to be blown away and recreated. Consequently, we implemented a custom scope for objects that were dictionary scoped, and part of the invalidation of a given dictionary involves clearing this custom scope. This lets Spring handle a nice form of automatic caching for these objects. You get the same object back every time up until the dictionary is invalidated, at which point you get a new object.
This helps not only with consistency but also allows the objects themselves to cache references to entities within the dictionary, safe within the knowledge that the cache will be valid for as long as they themselves are retrievable by Spring. This in turn lets us build these as immutable objects (so long as they can be wired via constructor injection), which is a very good thing to do anyway wherever possible.
This technique won't work everywhere and does depend heavily on the characteristics of the software (e.g. if the dictionary was modified regularly this would be horribly inefficient, and if it was updated never this would be unnecessary and slightly less efficient than direct access). However, it has definitely helped us pass off this management of lifecycle to Spring in a way that is conceptually straightforward and in my opinion quite elegant.

In my company we've created two custom scopes, one that will use Thread or Request and another that will use either Thread or Session. The idea is that a single scope can be used for scoped beans without having to change configuration based on the execution environment (JUnit or Servlet container). This also really comes in handy for when you run items in Quartz and no longer have a Request or Session scope available.

Background:
I work on a single web app that runs 4 different web sites under the same servlet context. Each site has its own domain name, e.g. www.examplesite1.com, www.examplesite2.com, etc.
Problem:
Sites sometimes require their own customised instance of a bean from the app context (usually for customised display of messages or formatting of objects).
For example, say sites 1 and 2 both use the "standardDateFormatter" bean, site 3 uses the "usDateFormatter" bean and site 4 uses the "ukDateFormatter" bean.
Solution:
I'm planning on using a "site" scope.
We have a Site enum like this:
enum Site {
SITE1, SITE2, SITE3, SITE4;
}
Then we have a filter that stores one of these Site values in the request's thread using a ThreadLocal. This is the site scope's "conversation id".
Then in the app context there'd be a bean named "dateFormatter", with 'scope="site"'. Then, wherever we want to use a date formatter, the correct one for the user's current site will be used.
Added later:
Sample code here:
http://github.com/eliotsykes/spring-site-scope

Oracle Coherence has implemented a datagrid scope for Spring beans. To sum it up:
A Data Grid Bean is a proxy to a
java.io.Serializable Bean instance
that is stored in a non-expiring
Coherence Distributed Cache (called
near-datagridbeans).
Never used them myself but they seem cool.

Apache Orchestra provides SpringConversationScope.

In a Spring Batch application, we have implemented an item scope.
Background
We have lots of #Service components which compute something based on the current batch item. Many of them need the same workflow:
Determine relevant item parts.
Init stuff based on the item.
For each item part, compute something (using stuff).
We moved the workflow into a base class template method, so the subclasses implement only findItemParts(Item) (doing 1 and 2) and computeSomething(ItemPart) (doing 3). So they became stateful (stuff initialized in findItemParts is needed in computeSomething), and that state must be cleared before the next item.
Some of those services also involve injected Spring beans which are also derived from the current item and must be removed afterwards.
Design
We implemented an AbstractScopeRegisteringItemProcessor which registers the item and allows subclasses to register derived beans. At the end of its process method, it removes the item from its scope context, and the derived beans using DefaultSingletonBeanRegistry.destroySingleton.
How it worked out
It works, but has the following problems:
We did not manage to get the derived beans cleaned up without registration (just based on their #Scope). The concrete processor must create and register them.
AbstractScopeRegisteringItemProcessor would have been nicer using composition and dynamically implementing all interfaces of the underlying processor. But then the resulting #StepScope bean is a proxy for the declared return type (i.e. AbstractScopeRegisteringItemProcessor or ItemProcessor) without the required callback interfaces.
EDIT
With the aid of #Eliot Sykes's solution and shared code plus #Cheetah's BeanDefinition registration, I was able to get rid of the registration as singleton beans. Instead, ItemScopeContext (the storage used by both the processor and the Scope implementation; Java-configured via a static #Bean method) implements BeanDefinitionRegistryPostProcessor. It registers a FactoryBean whose getObject() returns the current item or throws an exception if there is none. Now, a #Component annotated with #Scope(scopeName = "Item", proxyMode = ScopedProxyMode.TARGET_CLASS) can simply inject the item and need not be registered for end-of-scope cleanup.
So in the end, it did work out well.

A spring locale scope based on the users locale wihtin a web application
See related wiki page

In my company, we have also implemented spring custom scope. We have a multi tenant system where every customer can customize settings. Instance based scope of ours, caches the beans which are customer specific. So each time user of a customer logs in, these settings are cached and reused again when other users of the same customers sign in.

I once used a kind of conversation scope to store some objects in the session scope, in order to keep them when re-entering the same page, but limited to a single page to avoid to leave useless objects in the session. The implementation just stored the page URL and cleaned the conversation scope on each page change.

Related

Is each Play framework web request handled with a new dependency injected controller instance, but then what about static controller methods?

My questions are about the lifecycle of controllers in the Play framework for Java, if the controllers are stateful instances or stateless with static methods, and how to use dependency injection in the controller code.
Is each web request handled by a new instance of a Play controller class, i.e. can a controller store state in fields such as services injected into the controller constructor?
(where in the documentation is it explained?)
Has the Play framework changed since earlier versions (and if so, at what version?) regarding if controllers are stateful instances or stateless controllers with static methods?
Where can you see code examples about how the framework injects services into a controller instance when stateful controller is used and example of how to inject services into a static controller method?
Regarding the latter, i.e. injection into a static method I suppose that would either have to be a parameter to the method which the frameworks will add, or if not possible you maybe instead will have to use a service locator from within the method e.g. instantiate a Guice module class and then use "injector.getInstance" from within the static controller method.
This subject is touched in the section "Dependency injecting controllers" at the following page:
https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection
However, it does not show with code how to actually inject services into a controller instance (but probably the same way as other "components" i.e. with #Inject annotation) and certainly it does not currently show how to use DI with a static controller method.
I am confused about these things because I have not found documentation being clear about my questions, and I have also read in a Play book (from 2013) that the controller methods should be programmed as stateless and the controller methods should be static.
However, when now using activator for generating a Play application for Java with the latest Play version (2.4.6) I can see that the generated Controller method (Application.index) is NOT static.
Also, at the following documentation page, the controller method is NOT static:
https://www.playframework.com/documentation/2.4.x/JavaActions
This is confusing, and since it is VERY fundamental to understand whether or not each request is handled by a Controller instance or not (i.e. if state can be used) I think this should be better documented at the page about Controller/Actions than the current documentation (the above linked page) which is not explaining it.
The documentation about dependency injection touches the subject about static and non-static methods at the section "Dependency injecting controllers" mentioning "static routes generator" but I think it should be better explained including code examples.
If someone in the Play team is reading this question, then please add some information to the above linked pages, for example please do mention (if my understanding is correct) that in previous versions of Play the controller methods were static and for those versions you should never store state in fields, but in later versions (beginning from version x?) each request is handled by an instance of a controller and can therefore use state (e.g. constructor parameters injected by the framework).
Please also provide code examples about injection used with static controller methods and injection into stateful controller instances with one instance per request.
The section "Component lifecycle" in the dependency injection page only mentions "components" but I think it should also be explicit about the controller lifecycle and its injection, since it is such a fundamental and important knowledge to communicate clearly to all developers to avoid bugs caused by misunderstandings about being stateful or not.
Is each web request handled by a new instance of a Play controller class, i.e. can a controller store state in fields such as services injected into the controller constructor? (where in the documentation is it explained?)
As far as I can tell, controllers are by default singleton objects. This is not clearly documented, but it is implied that controller instances are reused. See the migration guide for Playframework 2.4:
The injected routes generator also supports the # operator on routes, but it has a slightly different meaning (since everything is injected), if you prefix a controller with #, instead of that controller being directly injected, a JSR 330 Provider for that controller will be injected. This can be used, for example, to eliminate circular dependency issues, or if you want a new action instantiated per request.
Also, check this commend made by James Roper (Play core committer) about if controllers are singleton or not:
Not really - if using Guice, each time the controller is injected into something, a new instance will be created by default. That said, the router is a singleton, and so by association, the controllers it invokes are singleton. But if you inject a controller somewhere else, it will be instantiated newly for that component.
This suggests that the default is to reuse controller instances when responding to requests and, if you want a new action per request, you need to use the syntax described in the migration guide. But... since I'm more inclined to prove and try things instead of just believe, I've created a simple controller to check that statement:
package controllers
import play.api._
import play.api.mvc._
class Application extends Controller {
def index = Action {
println(this)
Ok(views.html.index("Your new application is ready."))
}
}
Doing multiple requests to this action prints the same object identity for all the requests made. But, if I use the # operator on my routes, I start to get different identities for each request. So, yes, controllers are (kind of) singletons by default.
Has the Play framework changed since earlier versions (and if so, at what version?) regarding if controllers are stateful instances or stateless controllers with static methods?
By default, Play had always advocated stateless controllers, as you can see at the project homepage:
Play is based on a lightweight, stateless, web-friendly architecture.
That had not changed. So, you should not use controllers' fields/properties to keep data that changes over time/requests. Instead, just use controllers' fields/properties to keep a reference to other components/services that are also stateless.
Where can you see code examples about how the framework injects services into a controller instance when stateful controller is used and example of how to inject services into a static controller method?
Regarding code examples, Lightbend templates repository is the place to go. Here are some examples that use dependency injection at the controllers level:
https://github.com/adrianhurt/play-api-rest-seed
https://github.com/knoldus/playing-reactive-mongo
https://github.com/KyleU/boilerplay
Dependency Injection with static methods is not supported, and that is why Playframework stills offers old apis to use with static methods. The rule of thumb here is: choose between DI and static methods. Trying to use both will just bring complexity to your application.
Ok, thank you marcospereira.
I have now also confirmed that you indeed get different instances (different toString values which can be printed/logged in a controller method) of the controller for each request.
For those who are interested, the solution (to get different instances of controller class for each request) is to use for example the following:
GET / #controllers.Application.index()
instead of the following:
GET / controllers.Application.index()
in the file "conf/routes"
AND to also use the following:
routesGenerator := InjectedRoutesGenerator
instead of the following:
routesGenerator := StaticRoutesGenerator
in the file "build.sbt"
Regarding the statement that Play has a "stateless" architecture:
Maybe I am wrong, but as far as I understand the terminology, the "stateless" means that the web server does not store any state between requests?
The word "stateless" does not mean that a controller instance can not use fields, e.g. injected into the constructor.
If an injected object is stored as a field in a controller, then that field is a "state" of the controller.
Therefore, even if you use "InjectedRoutesGenerator" and the "#" prefix to get "stateful" controller instances, that injected "state" is only stored within one request, so you can still say that the framework itself is "stateless" since the server does not store any state between multiple requests.
Please do correct me if I have misunderstood something about Play being stateless.

What does it mean to "proxy a bean"?

At work and online I keep hearing the term "proxy" with respect to enterprise Java development. For example, metrics-spring uses this phrase:
This module does the following things:
Creates metrics and proxies beans which contain methods annotated with
#Timed, #Metered, #ExceptionMetered, and #Counted [emphasis mine]
I'm unfamiliar with a lot of the language in the Java ecosystem of frameworks and libraries. I feel like I have a good understanding of what a bean is, but I'm still not clear about how one would proxy a bean.
What does it mean to proxy a bean?
Typically, you have a bean like
Bean bean = new Bean(); // actually created by the context
With this, you can do anything that the Bean class declares as behavior (invoke its methods).
There are times where it would be nice if you could, for example, track how long a method invocation takes.
You could do
long start = .. // get start time
bean.invoke();
long end = .. // get end time
// end - start
But doing this for each method invocation sucks. So, instead, patterns, architectures, and styles like Aspect Oriented Programming exist.
Instead of the Bean above, you'd have
Bean bean = new TimingBean(new Bean()); // again done by the context
where the TimingBean is a proxy type that extends and implements all the types that Bean extends and implements. For all intents and purposes it is a Bean, but it adds a bunch of additional behavior before delegating each invocation to the Bean object. In this case, it would track how long each of Bean's method's took to execute.
Basic Spring uses JDK proxies and CGLIB proxies. Here are some differences between them.
It uses this for its scheduling and asynchronous invocations. It uses it for transactional support with databases. It uses it for caching. It even uses it for its Java based container configuration.
Proxying means that your client code thinks it's talking to one bean, but a proxy is really doing the listening and responding.
This has been true since early distributed client/server computing models like CORBA. A client would interact with an interface type as if it existed in their memory space, but they were really talking to a proxy that would handle all the messy details around marshalling request data into a request, communicating over the network to the remote object running on a server, and unmarshalling the response back to the client.
Spring uses this model for remoting. It also forms the basis for its aspect oriented programming model. Your code thinks it's dealing with a particular interface; Spring can weave in advice before, after, or around that instance and perform cross cutting operations like logging, transaction management, etc. on your behalf.
Some frameworks rely on a mechanism called instrumentation, which in short means to build a proxy of a given compiled bytecode, adding some code to it in some places we judge useful. This would implement many kinds of tasks, between them for example, adding a kind of profiling to a spring bean, as this library claims to do.
The Spring engine returns heavily instrumented proxies of every managed bean it offers - this way, you can use Spring declarative transaction handling, for instance. You would write "naive" daos without an actual connection handling, and "naive" service classes using the daos without an actual transaction handling - the instrumented proxies will include the boilerplate code with the connection instantiation, commits, rollbacks...
I hope this is of any help

Best Practice In JSF for Forms, Datatables, etc

Should I have a bean for every form, datatable etc in JSF?
For example, I have a form for registration, which simply has 2 fields and a button which are:
nickname, password, submit
Should submitting this form go to a RegistirationFormBean or somewhere in UserBean or UserServiceBean?
What is the best practice?
Thank you.
To decide whether or not you should create a #ManagedBean exclusively for a component of the page (e.g. form, datatable), I believe you should think about the modularity of your design.
The 1st question you should ask yourself is: Will the component be re-used in many pages?. For example, on sensitive pages such as ChangePassword or DeleteAccount, usually, you will ask the user to enter the current password to validate his identity before performing any logic. In this case, you should definitely have an exclusive bean for the validating password component so that you can re-use the component again and again without having to re-code the validating function every time.
Secondly, I usually use #ManagedBean as a place to hold all the related functions that work toward the same goal. This grouping of functions can be pretty subjective. For example, I can have a page called CreateProduct.xhtml with a bean called CreateProductBean that has all the functions for creating a product. In this case, it's like 1 bean per view. Another way is to have a bean called ProductManager that has functions for everything related to the Product object (i.e. create, read, update, remove). In this case, it's like 1 bean for many views (e.g. CreateProduct.xhtml, RemoveProduct.xhtml). For ease of future maintenance and division of work, I usually use 1 bean per view. The 2nd approach 1 bean for many views is also good on certain situations but I suddenly cannot think of an example yet :P... I will update my answer when I got a good one ;).
Thirdly, I prefer to follow the 3-tier MVC model and separate back-end logic away from the front-end. For example, to persist a new account in the database, I will inject an #EJB or a #WebServiceRef to ask the back-end system to perform the necessary logic. It's definitely more maintenance friendly in the future :).
So, using your RegisterAccount example, I will have
1 bean called UserExistenceValidator to check if a nickname exists in the database. During registration, I can throw an error if the user chooses a nickname that is taken. I can also use this bean to check if a user exists in the AddFriend.xhtml page.
Another bean called RegistirationFormBean to capture a user's inputs and talk to the back-end to persist the new account.
Its actually a pretty interesting topic to tweak any JSF lover's brain, so I could not resist myself and I would like to go with detail explanation.
One of the very interesting and significant cause behind the invention of JSF was, wiring client side event to server side application code like any swing application and getting rid of handing of request and response object explicitly. Like any swing application, we can now simply bind any client side event (say, button click) with some server side code to handle that event, without worrying the facts and complexities of writing an web application.
As a result when designing any web apps, that uses JSF, the designer can focus on the user experience as easily as designing an event driven swing application. So as the consequence, you design the view pages and identify the events to do tasks and navigate between the views. Finally you write some server side codes to be executed in those events, to do the job you want. Those server side codes reside in your managed beans.
If we classify based on the type responsibility, there are several types of managed beans:
Model Managed-Bean
Backing Managed-Bean
Controller Managed-Bean
Support Managed-Bean
Utility Managed-Bean
You will find the details of each of the type in this article.
Your problem is, how to distribute the responsibilities of Controller Managed-Bean. There are several issues to consider, while you are distributing this kind of responsibilities:
The complexity of the task to do.
Re-usability of it.
Modularity in terms of responsibility (type of jobs to do).
Modularity in terms of business perspective.
Decoupling the responsibilities. etc.
You can design your system to with a single controller for all the views of your simple CURD operations of a model. But if you need to handle multiple complex transactions in your single create operation, then separating the operations to multiple controllers, would be a better design. Though your registration procedure is pretty much simple, you should use a separate controller to handle the task. Because it will not be a good idea, to put any task in the same managed bean, that is not simple and related enough to reside with the task "registration". I think this, concludes your query!
you should a data transfer object bean and a domain bean for ui submission and for persistence in db respectively.
using a controller class, process your ui jsf submission data and create a clean domain bean and use this to persist.
the best practice should always de-couple processes/entities if possible.
also your dto bean might have accessory and more data than your domain bean which u might require for several purposes.
In similar situations, I always have a UserManagedBean that handles user relative operations, such as login, registration, change password, etc...
To deal with these operations, I put an attribute in the UserManagedBean of type User (or whatever class name) which corresponds to the persisted data related to users (usually in DB table user).
In your case nickname and password are attributes of the User class. As for the submit it will invoke a method in the UserManagedBean to authenticate user:
<h:inputText value="#{userManagedBean.user.nickname}"/>
<h:inputSecret value="#{userManagedBean.user.password}"/>
<h:commandButton value="Login" action="#{userManagedBean.loginUser}"/>
Of course, the loginUser method will invoke a call to the service layer which will invoke DAO layer to check credentials against DB (or other storage).
If the login is successful, the user attribute in our managed bean (which should be session scoped) is initialized with returned object from DB.

Why would we use custom scope in spring? When is it needed?

Can any one please help me in understanding custom scope. I went through manual and through many online example and understood how it is being implemented. But, I am still not clear why we need a custom proxy, and why we will go for, limiting the scope of the bean.
As i know that for a singleton- we use singleton when we want a single bean to be given to all references & we use prototype when we want a new reference to be given each time the bean is referenced.
Now my understanding regarding Custom scope is
Custom Scope- we use custom scope as a mid-way between the two that is neither we want to pass single reference nor a new reference every time.. but then it is more close to singleton where we are passing the same bean every time, just from our preferred location(such as underlying threadlocal or map).
please do help me making my concept clear ..The main question here is Why custom scope ? and When is it required?
In different context. For example - in a web application. Two scopes are defined there - "request" and "session". However, these are sometimes not sufficient. Often there is a need for a "flash" scope (lasts for one request and the subsequent redirect) or "conversation" scope (lasts for a sequence of requests forming a conversation).
In such, and similar cases, a custom scope is used.
That actually depends on the problem at hand. For instance, you might want to create a pre-defined number of instances of a particular bean, but not more than that. So until this number is met, you keep creating new instances, but once the number is met, you return existing instances in a balanced manner.
This could be applied to a problem where the instance takes up significant amount of resources (ex. memory) but speeds up the application if a new instance is used. So you could create a feasible amount of new objects when needed, and delegate into existing ones when the number of instances go beyond the that amount(compromising performance over resource utilization).

Removing type checking by using Spring bean id's

I've written a state machine for navigating an automated telephone system, where each state is represented by its own Java class file, for a total of 50+ classes. Rather than write the instantiation and factory code myself, I decided to use Spring for bean definition and dependency injection. This works fine, however I have lost compile-time type checking by moving from:
State next = getState(Instructions.class);
to
ApplicationContext ctx = ...
State next = ctx.getBean("instructions", State.class);
Instead of having compiler checks that I've specified a real, existing state, I now have to rely on the id being spelled properly in both my source code and the bean xml.
Is there a better way to do this? I haven't worked extensively with Spring since early 2.0 days, so I don't have much real world experience to draw on. What are the drawbacks and advantages of this approach? Is there is something extra I could to to verify proper id strings are used?
Consider using Spring autowiring and in your class have:
class StateMachine
{
#Autowired
State next;
}
You can also use qualifiers to select amongst the different implementation you may have of State.
Turn off lazy initialization of Spring, and you'll at least cure the type safety department. You could also consider a 'grand central station' bean into which all of the states are inserted by name, this resulting in a yell if any go missing. You can still mispell in your Java code.
I would personally go about it one of two ways:
1) If only a few states needed access to a few other states, I would inject those directly (like Steve said in his answer):
#Inject
public setInstructions(Instructions instructions) { ... }
2) On the other hand, if any state needs access to any other one, no one wants to inject the other 49 states into each of the 50 classes, so I would have one central class that had all 50 injected and basically build my state machine in that class.
Spring really is a factory when it comes down to it, but tying yourself to the Spring API kind of goes against their philosophy, and as you mentioned, you lose type safety.

Categories

Resources