Combine two maven based projects on two frameworks - spring

I have two maven projects say MvnSpring and MvnGuice.MvnSpring is working on spring and hibernate frame works.
And MvnGuice is working on google guice and mybatis. I need to combine both the features together.
Both are following singleton pattern. I need to get some class of MvnSpring in MvnGuice while coding. So that I created a jar of MvnSpring and put it in .m2 repository and give the dependacy details in MvnGuice. Now I can import classes of MvnSpring in MvnGuice classes.MvnSpring uses spring dependency injection and MvnGuice uses guice dependency injection for object creation. Now in MvnSpring flow is MSserviceImpl(implements MSservice) > MSdaoImpl(implements MSdao). Now I need to call MSService class from MvnGuice. Then at run time it shows error like MSService class is null. Then I made a guice dependency injection for MSService class in MvnGuice. Now the control reaches MSserviceImpl but now MSdao is null at here. Is it possible to start MvnSpring along with MvnGuice. I hope then I can solve the issue.

While Spring and Guice are targeted at the same problem, IoC, they take very different approaches to solve it. They differ both in functionality and in how they are configured, where Spring has bean definitions and Guice uses bindings.
Fortunately they do have common grounds in that they both support JSR-330, a standards specification that defines a set of annotations. This enables you to write your singletons and describe the injections that they need without depending on either Spring or Guice.
This way you can share your singletons between projects irregardless of the framework you use in a particular project. I would not recommend using both Guice and Spring in the same project, except if there's a clearly defined separation between them. For instance you might use Guice for a module that is used by Spring code via a defined API that hides the fact that it internally is based on Guice.

There was already mentioned JSR-330.
For some cases it can be not enough, e.g., you have code:
final String className = config.getProperty(«serviceImpl»);
// Class.forName(name) and check required interface for type safety
final Class<? extends Service> serviceClass = Reflection.classForName(className, Service.class);
final Service service = injector.getInstance(serviceClass);
In different DI environments you are supposed to support both com.guice.inject.Injector.getInstance() and org.springframework.context.ApplicationContext.getBean() implementations.
There is the draft solution sdif4j Simple Dependency Injection Facade.
The idea of this project is to encapsulate different DI frameworks logic with own abstraction to extend default JSR-330 possibilities. Note, there is no public releases yet, but you can find ideas how to solve your problem or make an internal release in a fork.
The general issue, is that your both MvnSpring and MvnGuice projects are supposed to be based on JSR-330 (instead of guice/spring annotations) and org.sdif4j:sdif4j-api (or your own abstraction; only if Injector functionality is required). It is recommended to make guice and spring dependencies optional (to compile but not export) to allow the library clients to choose the DI themselves.
In your MvnCompineGuiceAndSpring you just declare sdif4j-guice or sdif4j-spring dependency (it is similar to slf4j usage) and configure your DI environment. You can find different examples in testing subproject.
Some more notes:
Spring default scope is singleton, Guice - prototype (Spring terminology). So, if you want a prototype bean, you can use:
#org.springframework.context.annotation.Scope("prototype")
#javax.inject.Named
public class TestPrototype {
}
The Spring #Scope annotation should be ignored by guice even if spring does not present in your classpath.
Also you have to declare all your Singleton beans with #javax.inject.Named and #javax.inject.Singleton annotation to support both Spring and Guice, like this:
#javax.inject.Named
#javax.inject.Singleton
public class TestSingleton implements ITestSingleton {
public TestSingleton() {
}
}
As with #Scope annotation, you can use #ImplementedBy(#ProvidedBy) guice annotations on your code (when feasible; be careful with it, in general it is not a good practice), that should be also ignored in Spring DI (in both cases if Spring exists in classpath or not).
Hope, that's clear.

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.

Implementing an interface is tight coupling?

It says here that
I would not recommend to use InitializingBean and DisposableBean
interface, because it will tight coupled your code to Spring
Does it make sense? I thought this would be just the opposite to tight-coupling.
Here the author means that if you let your application classes implement InitializingBean and DisposableBean interfaces (that are spring specific interfaces), then you are coupling your code with spring.
In future if spring renames these interfaces (unlikely though), or you stop using spring you will have to update your class code.
Instead if you use init-method and destroy-method attributes in your bean config, your class is independent of spring, i.e. there is no depedency of your class on spring specific classes.
Hope it helps.
I think the idea here is to not create any dependency on your code to spring annotations, see
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
When you explicitly declare this kind of dependency, you're coupling your code to spring jars.
In this other example - http://www.mkyong.com/spring/spring-init-method-and-destroy-method-example/ - it shows how you could use convention methods defined in the XML. No spring imports.

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.

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

Managing complexity in a dependency-injected app with a large number of beans

I'm working on an Spring application which has a large number of beans - in the hundreds - and it's getting quite cumbersome to use and document.
I'm interested in any experience you have with DI-enabled apps with a large number of beans which would aid maintainability, documentation and general usage.
Although the application is Spring-based with a couple of context files, I'm open to listening about suggestions regarding any DI container and about DI in general as well.
You can use component scan and autowiring features to dramatically decrease the amount of Spring XML configuration.
Example:
<beans>
<!-- Scans service package looking for #Service annotated beans -->
<context:component-scan base-package="my.root.package.service"/>
</beans>
Your service classes must be annotated in order to be automatically scanned:
package my.root.package.service;
#Service("fooService")
public class FooServiceImpl implements FooService{
}
You can also use the #Autowired annotation to tell Spring how to inject the bean dependencies:
package my.root.package.service;
#Service("barService")
public class BarServiceImpl implements BarService{
//Foo service injected by Spring
#Autowired
private FooService fooService;
//...
}
I found the following to be of use:
split your Spring configurations into multiple standalone configurations, and use Spring's import facility to import configuration dependencies (see here, section 3.2.2.1). That way you have a set of configurations that you can combine or disassemble as required, and they are all self-dependent (all the dependencies will be explicit and referenced)
Use an IDE that is Spring-aware, and allows you to navigate through the configurations via point-n-click on beans (references/names, to-and-from source code). Intellij works very well at this (version 7 and beyond, I think). I suspect Eclipse would do something similar.
Revise what you're injecting where. You may want to refactor multiple bean injections into one composite or 'meta' bean, or a larger component. Or you may find that components you once thought you'd need to inject have never changed, or never demanded that injectability (for testing, implementing as strategies etc.)
I used to work with a huge Spring installation, with hundreds (thousands?) of beans. Splitting the configurations up made life a lot more manageable, and simplified testing/creating standalone processes etc. But I think the Intellij Spring integration that came with Intellij made the most difference. Having a Spring-aware IDE is a major timesaver.
As #Wilson Freitas says, use autowiring. I daily work with a system that has few thousand spring managed beans using mostly autowired. But I think the notion of "retaining the overall picture" is slightly misplaced. As a system grows you can't expect to do that in the same way as you did on a smaller system. Using #Autowiring forces you to use stronger typing than xml-based spring, which again means you can use the dependency tracking features of your IDE to navigate in dependencies.
I really think it's suboptimal to think that you need to understand too much of the "full" picture when it comes to the spring configuration. You should be focusing on your code and it's dependencies. Managebility and maintainability are achieved by organizing this code well, naming things well and managing your coupling; all of the stuff that applies even if you're not using spring. Spring shouldn't change much, and with the approval of JSR-330, it may even seem like dependency injection will creep further "under the hood" of the runtime environment.
Our strategy is:
naming conventions, e.g.: fooService, fooDao, fooController;
property setters following these conventions;
autowiring by name (autowire="byName"); we had many problems with autowiring by type, especially on the controller layer

Resources