Spring integration - defining base beans in configuration - spring-integration

Is it possible to define, within XML, a standard Spring Integration bean as an abstract bean which can be overridden. The idea of course would be to minimize configuration.
For instance, say one needs several jms:message-driven-adapter beans, all which share some common properties. How could one define an abstract bean with those properties, and then override it with concrete beans which have just the parameters which are different between each instance?
Thanks

You cannot do it with the namespace; but the JMS message-driven adapter is a relatively simple component that you can define with normal <bean/> syntax. You would need to wire together a JmsMessageDrivenEndpoint which takes an AbstractMessageListenerContainer (DefaultMessageListenerContainer) and a ChannelPublishingJmsMessageListener in its constructor.
In general, taking a look at the namespace parser for each component will tell you what <bean/>s to define.
Another technique is to define a "mini" application context defining the endpoint with property placeholders and then create a new instance of the context each time, making the main context the parent.
The general technique is explored for outbound ftp endpoints in this sample. However, it does not make its contexts children (because it's not needed there). However, the README has a link to a forum thread that explains that mechanism, when used for dynamic inbound endpoints.

Related

Utility methods in application scoped bean

Do you think it is a good idea to put all widely used utility methods in an application scoped bean?
In the current implementation of the application I'm working on, all utility methods (manipulating with Strings, cookies, checking url, checking current page where the user is etc.) are all put in one big request scoped bean and they are referenced from every xhtml page.
I couldn't find any information on stackoverflow if the approach of putting utility methods in an application scoped bean would be a good or a bad choice.
Why I came across this idea is the need of reusing those methods in a bean of a wider scope then a request scoped bean (like view or session scoped bean). Correct me if I'm wrong but you should always inject same or wider scoped beans i.e. you shouldn't inject request scoped bean inside a view scoped one.
I think using utility methods from application scoped bean should be beneficial (there won't be any new object creations, one object will be created and re-used across all application), but still I would like a confirmation or someone to tell me if that is a wrong approach and why is it wrong.
As to the bean scope, if the bean doesn't have any state (i.e. the class doesn't have any mutable instance variables), then it can safely be application scoped. See also How to choose the right bean scope? This all is regardless of the purpose of the bean (utility or not). Given that utility functions are per definition stateless, then you should definitely be using an application scoped bean. It saves the cost of instantiating on every single request.
As to having utility methods in a managed bean, in object oriented perspective this is a poor practice, because in order to access them from EL those methods cannot be static while they should be. You can't use them as real utility methods in other normal Java classes. Static code analyzers like Sonar will mark them all with a big red flag. This is thus an anti-pattern. The correct approach would be to keep using a true utility class (public final class with private Constructor() with solely static methods) and register all those static methods as EL functions in your.taglib.xml as described in How to create a custom EL function to invoke a static method?
At least, this is what you should be doing when you intend to have a publicly reusable library such as JSTL fn:xxx(), PrimeFaces p:xxx() or OmniFaces of:xxx(). If you happen to use OmniFaces, then you could, instead of creating a your.taglib.xml file, reference the class in <o:importFunctions>. It will automatically export all public static methods of the given type into EL function scope.
<o:importFunctions type="com.example.Utils" var="u" />
...
<x:foo attr="#{u:foo(bean.property)}" />
If you don't use OmniFaces, and this all is for internal usage, then I can imagine that it becomes tiresome to redo all that your.taglib.xml registration boilerplate for every tiny utility function which suddenly pops up. I can rationalize and forgive abusing an application scoped bean for such "internal usage only" cases. Only when you start to externalize/modularize/publicize it, then you should really register them as EL functions and not expose poor practices into public.

Inject ConversationScoped beans within an asynchronous method

I need to call a method annotated with #Asynchronous in EJB from a ConversationScoped bean. Inside this method I create instances of some classes using #Inject to inject ConversationScoped beans.
Is it somehow possible to set the context of the asynchronous method to given Conversation?
I hope you can help me.
No, absolutely not. EJBs do per definition not run in web container, but in EJB container. In essence, having any web-related artifact/dependency (including javax.faces.* classes) inside an EJB class is a red alert. You're not supposed to inject/access any class from the client tier (the WAR) in the business tier (the EJB/EAR). Moreover, conversation scoped beans are tied to a HTTP request parameter and this information is nowhere available in an EJB container.
Whatever problem you're trying to solve and for which you incorrectly thought that this all would be the right solution, it has to be solved differently. As an educated guess, I think you just need to let the EJB fire a CDI event or take a callback argument.
See also:
JSF Service Layer

Unrecognized Spring cache annotations when self-invoking a method from within the same bean

Dear Spring Cache project community,
currently I'm implementing an Apache CXF-based Spring (version 4.1.5) web service endpoint using the contract 1st approach. Here, I observe when annotating a public method within my web service class, the Spring cache annotations "#Cachable" are ignored each time I call this method in a self-invoked way within the same bean. This could be proven when taking a look on the cache repository (via JMX) of the underlying cache provider (here: EhCache). There, no filling of the cache takes place.
After taking a look on the current Spring documentation below
Enable caching annotations and
The dispatcher servlet I assume it might be due to the fact that:
<cache:annotation-driven/> only looks for #Cacheable/#CachePut/#CacheEvict/#Caching on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for beans in your controllers, and not your services. See Section 17.2, “The DispatcherServlet” for more information.
Currently, an Apache CXF "CXFServlet" registered within the "web.xml" deployment descriptor is starting a Spring WebApplicationContext using the "cxf-servlet.xml" Spring application context file by default. There, the <cache:annotation-driven/> is located.
Or is it maybe due to the fact that I'm calling the #Cacheable annotated method from within the same Spring bean so that the generated Spring proxy is bypassed? Details can be found in the "Proxy mechanisms" chapter (9.6) of the Spring documentation as well.
But I do not know how to change the behaviour so that my method results are being cached. Do you have any ideas? Or are my assumptions I posted above incorrect?
Dear Spring community,
I found the important comment within the Spring documentation that approves my assumption:
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual caching at runtime even if the invoked method is marked with #Cacheable - considering using the aspectj mode in this case. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. #PostConstruct.
In consequence this means refactoring the code when relying on Spring AOP and its proxy mode technique or switching the mode from "proxy" to "aspectj" <cache:annotation-driven mode="aspectj"/>. This allows using self-invoking methods within the same class as AOP does static respectively dynamic weaving and so manipulates the byte code directly.

Backing bean organization in JSF

I have been thinking about this for a while now and have yet to come up with a best practice for how to organize my beans/classes in a JSF project for the presentation tier. Obviously there are many factors that come into play, but I would like to discuss. Here is my current line of thought:
Consider a basic JSF (still stuck on JSF 1.xx here unfortunately) application that contains a view page (view the data) and an edit page (add, update, delete the data). Here is how I would organize the project:
Request scoped BackingBean:
View related stuff (save status, render logic, etc.). Stuff that is only needed in one request
Actions, action listeners, and value change listeners. If they are applicable to more than one view, they can be separated into their own file.
Session scoped BackingBean:
Anything that needs to remain around longer than one request. Database data, SelectItems, etc.
This bean is injected into the request bean, and stores instances of any data objects
Data Objects:
It doesn't seem to make sense to make the data objects into beans, so they are stored separately. This would be things like User, Book, Car, any object that you are going to display on the page. The object can contain view helper methods as well such as getFormattedName(), etc.
DAO:
A non-bean object that handles all interaction with the business logic tier. It loads the data bean and prepares submits, etc. I usually make this a class of public static methods.
Converters, Validators:
Separate files
This seems to be all that is needed in your average JSF application. I have read through this: http://java.dzone.com/articles/making-distinctions-between, as well the replies here: JSF backing bean structure (best practices), but I never felt like we got a complete picture. BalusC's response was helpful, but didn't seem to quite cover a full app. Let me know your thoughts!
I think you are on the right track generally, however I would do a few things differently:
I would take your DAO layer and split it into two seperate layers, one pure DAO layer that merely is responsible from fetching data from various sources (Eg. database calls, web service calls, file reads, etc...). I would then have a Business Logic layer that contains passthroughs to DAO calls as well as any additional calculations, algorithms, or other general business logic that isn't specific to any one JSF view.
In the MVC pattern, your ManagedBean plays the role of the Controller, and as such should also be the repository for Presentation Logic (logic that is specific to manipulating the view or interacting between various View components). It will also tie your business logic into the event behavior as well.
I would not use public static methods for your Business Logic or DAO layer. This doesn't lend itself well to automated unit tests and prevents your app from utilizing Dependency Injection frameworks like CDI or Spring. Instead create an interface for your BO's and DAO's and then an implementation class for this.
On that note, utilize a Dependency Injection Framework like CDI or Spring :) It will allow you to automatically inject Business Logic objects or DAO's into your ManagedBeans as well as your unit tests. It will also allow for you to swap implementations or DAO's without any coupling to code in other layers of your application.

Spring #Controller lifecycle

I am new to Spring MVC and would like to know how it handles requests, more specifically:
I would like to know how a Spring
#Controller's life cycle relates to
that of a Servlet?
I would also like to better
understand what are the best
practices for multi-threaded
enviornments (e.g. like in Servlets,
are class attributes visible to
multiple HTTP requests as objects are
reused from the pool)?
A controller (as any spring bean) has a scope.
At best your controllers should be of scope singleton. In that case it is very much like servlets, and:
they are created only once, during the application context startup (and destroyed when the context is destroyed)
you should not use any instance variables (as this is not thread-safe)
If your controller scope is request or session, then you can have instance variables, and an instance of the controller is created on each new request/session.

Resources