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

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.

Related

Why use Spring framework when we can achieve loosely coupled code using interfaces?

As far as i know we use spring IOC so that it becomes easy for developer to check the xml file to identify and control the flow of code by providing the dependencies explicitly.
But if we use autowire, developer actually has to check the code to identify which implementation is autowired to given class
same thing could have been achieved without actually using spring framework for example, so why we need spring or what is the real advantage of using springs in this case.
Interface Vehicle {
.....
}
Class Car implements Vehicle {
......
}
Class Example {
Vehicle v = new Car()
}
Or
Class Example {
#Autowire
Vehicle v;
....
}
This is a very good question!. Now for answer in the best way I consider that a little bit of story can be helps.
Spring was born in the EJB era in which all was configured in xml and Spring originally was a java framework for provide IOC POJO based. In this era was totally normal configure our application in xml and spring was a good choice because we can benefits of IOC without the EJB complexity and in a vendor free manner, EJB is not totally application server free because some times the vendor implementation especially for vendor specific configuration brings the application to do not totally portable, spring was a successful framework because was a solution for almost all the problems of an EJB application. Then the success of framework brings the framework to grow and include other capabilities like data access, web integration and more other integration and capabilities.
In this years also JavaEE grows and in JavaEE 6 was born CDI Spring provide a xml, annotation, java config groovy, kotlin dsl bean configuration in order to achieve flexibility and give a comfortable programming and configuration model, think about all the people that come from JabaEE 6+ that usually use #Inject for provide DI. Now said all this DI capability are to discretion of the developer.
In my opinion use #Autowired is dangerous because this brings you to Spring for ever and many issue of DI can arrives in case of more that one bean are configured. To enforce the effort of spring team to give you confort and free choice of configuration starting from Spring 4.3.x you can do a think like
interface Vehicle {
}
class Car implements Vehicle {
}
class Example {
private final Vehicle vehicle;
Example(Vehicle vehicle) {
this.vehicle = vehicle;
}
}
#Configuration
class Config{
#Bean
public Car car(){
return new Car();
}
#Bean
public Example example(Vehicle car){
return new Example(car);
}
}
#RestController
class Enpoint{
private final Example example;
Enpoint(Example example) {
this.example = example;
}
the your business code now is totally free from spring even the constructor on the rest controller do not required #Autowired annotation, of course you have configure it.
On the end I can say that you should use Spring not because Spring provide IOC, this can be achived in a Plain Java manner, whith Google Juice, Spring and many other IOC framework but I suggest you to use Spring for all the related project that give you many capabilities production ready like, Spring web for blocking IO, Spring WebFlux for no-blockin IO, Spring Integration for EIP, Spring batch for Enterprise ready Batch, Spring Cloud for Cloud native application and more and more, the power of Spring to day is the flexibility and completeness, of course, the law of spider man is valid! from great powers we have great responsibilities.
Spring give you many possibility but then is the developer responsibility to choose the best. Annotation give you speed especially during the prototyping but then is too rigid.
I hope that this long reflection give you an answer of your doubts
In this way, the problem is the Vehicle ā€œvā€ is coupled tightly to Car, every change of output generator may involve code change. If this code is scattered all over of your project, every change of the Vehicle will make you suffer seriously.

Injecting spring beans into legacy web app POJOs [duplicate]

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.

Dynamic dependency injection in jsf 2 or spring 3

I have 3 implementations of an interface, and in order to instantiate one of them I need to check a parameter from the database.
I was planning to do it with the factory pattern, but since I'm using JSF 2 dependecy injection in the rest of my application I was wondering if
there's a way to do that, is it possible to do the dependency injection dinamically?
can I indicate somehow a method or something to pick up the correct implementation at each moment?
For the backend I'm using spring core, so a way to do that with the spring context would work to.
I'm using Annotations for everything (#Autowired for Spring, #ManagedProperty for JSF).
EDIT: The project will be deployed on a Tomcat server.
I suggest you to use CDI in your JSF project, you can then use programmatic injection.
You should start with adding CDI Qualifiers to your interface implementations (you will basically create custom annotation for each implementation - tutorial). Then you can use something like
#Named //similar to ManagedBean
#RequestScoped
public Bean {
#Inject
#Any
Instance<YourInterface> yourInterface;
public void someMethod() {
if(someCondition) {
InterfaceImpl impl = yourInterface.select(new SomeOfYourQualifiers()).get();
}
}
}
Source
Also you you don't have to use Autowired in favour of Inject. I am also sure that there is some Spring way how to to this but I will leave that to some Spring expert here:-)
EDIT
According to this answer is really possible to run CDI on Tomcat. You will also find some tutorials like this one. And Spring approach could be using AutowireCapableBeanFactor but as I say, I don't know Spring much so it's just a wild gues:-)

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 :)

Resources