Injecting spring beans into legacy web app POJOs [duplicate] - spring

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
In order to provide POJOs in my legacy web app (Tomcat 8.0.26) with the ability to send ActiveMQ messages I've taken the recommendation to introduce Camel (2.15.2) / Spring (4.2.1) into the app to purely for the purpose of managing pooled MQ connections. I'm hoping there isn't an easier way.
Doing things the Spring way I'm thinking everything would need to be based around an MVC architecture with HTTP servlet aware controllers having access to the servlet context and therefore the Spring context in order to inject beanFactory beans into classes annotated with #Controller and #Service (and in fact there must be a Spring #Controller class that enables Spring to inject the #Service class.
However, as I've stated this is legacy code that will not be using the spring web framework.
After much pain it seems that the only way I can get beanFactory beans injected into my POJOs is to go the AspectJ and Weaving route. Before I go down this road can someone tell me that this is currently the best approach (what I've read describing this solution is from 2011 Can't get Spring to inject my dependencies - Spring Newbie) ? Can you point me to documentation and a working example?
Many thanks.

1) aspectj with #Configurable
In your #Configuration annotated class/es
you can add some more annotations
#Configuration
#EnableLoadTimeWeaving(aspectjWeaving = EnableLoadTimeWeaving.AspectJWeaving.ENABLED)
#EnableSpringConfigured
#EnableAspectJAutoProxy
to enable aspectj and the #Configurable annotation,
you need to import the aspectj lib to your project and add the spring tomcat instrumentable java agent in your tomcat lib folder (give a look here, it exaplains how to configure tomcat) http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/instrument/classloading/tomcat/TomcatInstrumentableClassLoader.html
this is not going to help you if you are going to create your pojos using "new"
MyPojo p = new MyPojo(); // no black magic for this, you will need to satisfies the dependencies yourself) but that would be helpful for example when you load some entities through a framework like hibernate and you want to inject something into them.. #Configurable it's an option that can be evaluated in those cases, for what you describe I would rather not use it.
2) You can have some static methods that uses some static set spring-beans and use them from your pojos, something like
class Util{
private static SprintBeanWithJmsSupport x;
public static setSpringBeanToHandleJmsMessages(SprintBeanWithJmsSupport x){
Util.x = x;
}
public static sendJmsMessage(JmsMessage m){
x.sendMessage(m)
}
}
and you can go with Util.sendJmsMessage(...)
this is a bit shitty but it does the work, I don't personally like this approach
3) set your spring beans in your pojo when they need to use them (maybe behind some nice interfaces that suit your domain)
if you go with spring mvc you will likely end up having some controllers that will use some services (generally they handle security / db access and are the entry point to start the "use cases"), as everything wthin these layers is handled by spring it will be very simple to pass the spring-bean to handle jms messaging to your pojos, this seems to me quite a nice way to handle the problem
I went mostly based on memory and something may not be completely accurate, plus my english is .. what it is, so hope this can be helpful anyway.

Related

Is it ok to use non-annotated classes (beans) in spring framework?

I have a spring-boot project. Some of the classes I am using it in the 'spring' way, meaning that they are annotated by "#Service", "#Repository", "#Autowired". At the same time, I have lots of classes, which are only used in the normal Java way, meaning that there are no any Spring annotations, and they are created in the standard way of constructing an object in a constructor.
For example, one of the non-annotated classes is:
public class GenericTree<T>
{
private GenericTreeNode<T> root;
public GenericTree ()
{
root = null;
}
public GenericTreeNode<T> getRoot ()
{
return this.root;
}
public void setRoot (GenericTreeNode<T> root)
{
this.root = root;
}
...
}
Is it OK or normal to have a mixure of classes with or without Spring annotations? Probably, I could convert all non-annotated classes into annotated classes by using Spring's annotation markers. Does that really benefit or is it necessary?
BTW, my application's main logic and functions are not web-centric, although they are created as a Spring project. The reason I created in Spring is I want to provide a restful service for my interface so that I can easily test in browser in development, and others can use it with Restful service.
Yes it is ok.
Keep in mind that annotations are not Spring exclusive. Annotations were introduced in Java 5 and they are just meta data for your Java code. This meta data can be useful at:
Compile time
Build time
Runtime
You can even create your own custom annotations and annotate your code with them.
Spring framework comes with some annotations and each one of them has its purpose, but that doesn't mean you have to annotate all your classes with Spring annotations when you are using this framework.
When you annotate your classes as Spring Beans, they become part of the Spring Application Context, thus making them available to be injected with the #Autowired annotation (Spring framework is based on the dependency injection design pattern). But Spring annotations have other implications too, I cannot go into the detail of each one of them but for example, you have to consider that the default scope of annotations like #Bean, #Component, #Controller, #Repository, #Service is Singleton. So whenever you annotate a class with one of these annotations and you don't define a scope, what you get is a singleton class shared all over your application. Other scopes are:
singleton
prototype
request
session
application
websocket
Taking in consideration your GenericTree class, does it make sense to annotate an abstract data structure class as a Spring Bean? Probably not.
So yes, when you develop an application based on Spring framework the normal thing is to have a mixture of Spring annotated classes and regular POJO's.
I recommend you to read the Spring framework documentation, learn what dependency injection is and the purpose and implications of the most used Spring annotations.

Java EE 6 / 7 equivalent for Spring #Configuration

Is there a Java EE 6 / 7 equivalent annotation for Spring's #Configuration?
If the answer is yes then are the equivalents for its surrounding annotations, such as #ComponentScan and #EnableWebMvc?
I did, of course, look for it in Java EE 6 / 7 (I admit I skipped a paragraph here and there), in javadocs (specifically among annotations), in Spring doc, tutorials, blogs, SO and Google.
JEE CDI has also an annotation of creating bean programmatically and exposing them, so it offers bean factories, called producers:
https://dzone.com/articles/cdi-and-the-produces-annotation-for-factory
CDI offers Producer methods (annotated with #Produces) which is the equivalent of #Bean in spring. You can than implement Producers classes that are beans which contain a bunch of producer methods. However, this is by far not as powerful as a spring configuration since as far as I am aware of, there is no possibity to e.g. "import" other configurations (producer classes).
This makes it especially difficult to test CDI applications.
You can either
heavily use mocks to test a single CDI bean to totally avoid injected objects
blow up your test class just to create the instance under test with all dependencies
use testing frameworks like CDI-Unit that creates the beans for you
With 1. Test Driven Development becomes almost impossible and tests have always to be adapted when implementation changes, even if the contract does not change.
With 2. you end up in a lot compiler errors in tests as soon as dependencies between your Beans change
With 3. you need to point your testing framework to the implementation of your beans. Since there exists no Configuration that knows about all beans, the test needs to know about it. Again, if things change your tests will break.
I admit... I don't like CDI ;-P
The javax.servlet.annotation package defines a number of annotations to be used to register Servlet, Filter, and Listener classes as well as do some other configuration, for example, security.
You can also use the ServletContainerInitializer class to configure your ServletContext through Java instead of through the XML deployment descriptor. Spring provides its own implementation of ServletContainerInitializer in which case all you have to do is create a class that implements WebApplicationInitializer and does servlet, filter, and listener registration and leave that class on the classpath.
Examples abound in the javadoc.

CDI Bean accessing Spring beans?

I know this sounds strange, mixing CDI (Weld) and Spring for the controller.
But imagine this situation :
With CDI, i can make use of the #ConversationScoped, which is one of my requirement (And so far i dont know whether i can use spring for this kind of scope, because if i can, i could just replace Weld with Spring, with the el-resolver in faces-config.xml)
My services objects(#Service) along with the DAOs(#Repository) are to be managed by Spring
Now one question arise is that, inside my controller, how can i access my service object ?
Something like this wouldnt work i think :
#Named
#ConversationScoped
public class MyBean {
#Named
private SomeOtherBeanManagedByCDI myOtherBean; // this will work
#Autowired
private MySpringBean mySpringBean; // dont think that this will work
....
}
Any ideas on how to make use of spring beans inside a cdi bean ? Thank you !
update
I've just tested the solution from this article, and so far it works fine, and i feel relieved.
Thank you !
Rick Hightower wrote a nice Extension library which supports to inject Spring beans into CDI beans and vice versa:
http://rick-hightower.blogspot.com/2011/04/cdi-and-spring-living-in-harmony.html
There is still a good accepted answer and some good edits in the OP, but I think there still is time to point out the Seam Spring module.
Also, if you're trying to manage state across a series of pages, and want the effective of conversation management for Struts or JSF or Spring MVC, Spring Web Flow provides just what you need, complete with flow-scoped beans that live for the duration of a flow, more or less equivalent to a conversation in Seam / CDI. If you want a more long lived flow managment solution, the Activiti SPring module makes it dead simple to configure some beans that live for the duration of the process scope, akin to the functionality that Seam had for jBPM.

Am I allowed to declare a lifecycle interceptor on an interceptor?

I have my business bean defined thus:
#Local
#Interceptors(BusinessInterceptor.class})
public class MyBean implements SomeBean { ... }
And then I want my BusinessInterceptor to be configured with Spring's SpringBeanAutowiringInterceptor:
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class BusinessInterceptor {
#Autowired
private SomeSpringBean someSpringBean;
}
Is this allowed/legal? I'm getting errors (NPEs, mostly) suggesting that the fields in BusinessInterceptor have not been initialized properly.
I doubt this can work. If I understand well your scenario, you have basically two DI containers, one is Spring and the other the app. server itself. Each one manages different elements. The BusinessInterceptor is created by the app. server which is unaware of Spring -- the #Autowired bean is then not set.
( Note that Spring and EJB3 have become quite similar now. You can have the same functionalities as EJB with Spring. Spring has indeed declarative transactions, dependency injection and AOP facilities similar to EJB3 interceptors (these are the main managed features). On the other hand, EJB3 is now so lightweight that there isn't really a compelling reason to use Spring with with EJB3. See Future of enterprise Java: full stack Spring or full stack Java EE. But this does not answer the question, and is just a little digression of mine :)

Should I use Spring or Guice for a Tomcat/Wicket/Hibernate project?

I'm building a new web application that uses Linux, Apache, Tomcat, Wicket, JPA/Hibernate, and MySQL. My primary need is Dependency Injection, which both Spring and Guice can do well. I think I need transaction support that would come with Spring and JTA but I'm not sure.
The site will probably have about 20 pages and I'm not expect huge traffic.
Should I use Spring or Guice?
Feel free to ask and followup questions and I'll do my best to update this.
If you like the "do-it-all-in-Java" philosophy that Wicket follows, then you might prefer Guice over Spring. There is no XML configuration in Guice - it is all done using the Guice Module class.
For example, your Wicket WebApplication class might look something like this:
public class SampleApplication extends WebApplication
{
#Override
protected void init()
{
addComponentInstantiationListener(
new GuiceComponentInjector(this, new GuiceModule()));
}
}
The GuiceComponentInjector comes from the wicket-guice extension. Here's the Module:
public class GuiceModule extends AbstractModule
{
#Override
protected void configure()
{
// Business object bindings go here.
bind(Greetings.class).to(GreetingRepository.class);
}
}
In this example, Greetings is an interface implemented by a concrete GreetingRepository class. When Guice needs to inject a Greetings object, it will satisfy the dependency with a GreetingRepository.
I have put together a sample project that demonstrates how to build a Wicket/Guice application for Google App Engine. You can safely ignore the App Engine specifics and focus on how the Wicket-Guice integration works.
If you do end up going with Guice, definitely check out Warp Persist for Hibernate, Guice Servlet for Tomcat, and wicket-guice for Wicket.
Spring would probably give you more flexibility, but if you just need DI then Guice may be a better choice.
It is difficult to answer as Spring has so many features that would make the DAO more flexible, and works well with Hibernate. It would help if you had more requirements for what you are looking for.
Here are a couple of comparisons between Spring and Guice and Spring, Guice and Picocontainer.
http://code.google.com/p/google-guice/wiki/SpringComparison
http://www.christianschenk.org/blog/comparison-between-guice-picocontainer-and-spring/
Don't forget CDI/JSR-299, part of Java EE 6. You can use weld-wicket to integrate wicket with CDI.
(as long as you're using the weld implementation (as GlassFish v3 and JBoss 6 do), but the weld-wicket is rather small so you could probably adapt it if needed).
I managed to get Wicket 1.4 + weld-wicket + wicket-contrib-javaee + EJB 3.1 + JPA 2.0 + wicket-security (SWARM) + Spring Security 3 + Spring 3 running together in a small proof of concept application. That's a bit too many frameworks though, will probably drop spring-security & spring as they appear redundant.

Resources