Spring annotations basic question - spring

As far as I understand, main purpose of dependency injection is to have all dependencies separated declaratively, so that we can easily review and change the dependency structure easily...right?
Then by using dependency annotations spread through out the code, aren't we just going back to non-centralized system (similar to simple new operator), which is harder to tweak?

#Autowired/#Inject annotations usually declare dependencies on interfaces rather than on concrete classes (as in the case of new), thus you still can control which implementations should be injected by controlling which beans are declared in the context. Also, these dependencies can be overriden manually.
#Component-family annotations can be controlled as well, since you can exclude particular classes from component scanning.

The purpose of dependency injection is to decouple the declaration of dependencies from the actual satisfying of those dependencies. How the declaration is done is an orthogonal issue.
#Autowired is a form of dependency declaration. Using #Autowired supports encapsulation. A class' injected dependencies are documented directly in the code instead of in another file.

These types of discussions have tendency to become religious so I'll stear clear of the "main purpose" definition and the semantics of whether this or that pattern is really and truly fulfilled.
I try to look at it like a tool that can offer certain features. For instance, using Spring (DI) is a good way to separate interfaces and implementations. Users of a particular interface need not know how to create the implementation (or where it resides). This is often something good. Using Spring also enables a whole lot of other stuff: AOP and AOP-driven features like transaction handling, scopeing and a whole bunch of pre-built integrations to other frameworks and technologies. Annotations make a lot of this easier and clearer and best of all, I don't have to use them where it's not practical or possible - there is always the option to configure it in XML instead.

Related

What is the right way to inject Spring Data repositories?

Modern Spring recommendations (Spring 4.x onwards) recommend not using field injection (with #Autowired or #Inject), and instead preferring constructor arguments. Several discussions about this here, here and the Spring Framework itself recommends constructor-based DI for mandatory dependencies.
In general I agree perfectly with the rationale, and in fact I haven't used any of the field injection mechanisms for years now.
What is bugging me however is the way we inject Spring Data Repositories. Of course these are mandatory dependencies, the service needs them to work. When one looks at the Spring Data documentation one finds that the reference documentation itself is using #Autowired field injection all over the place, precisely what was recommended as bad practice in the Spring Framework documentation itself.
Of course, it is no problem to have repositories use constructor injection. I have been using this for quite some time. However, sometimes components and services need quite a number of repositories. A service might be interacting with 7 or 8 database tables, and they would need to be in the same transaction.
How does one go about this to have neat code? Using constructor arguments is the safer approach, but leads you to have a huge number of constructor arguments. Setter injection does not seem to fit, these are not optional dependencies. Field injection is supposed to be plain wrong (even though the Spring Data doc uses it).
Is there any other approach one could use? I was tempted to aggregate related repositories in a separate #Component, at least the service constructor gets only one argument with this constructor. It does help a bit, but makes it even harder to interact with a new table (the new repository would need to be added to the aggregate, and the service would need to call the getter for it).
How is it supposed to be done neatly without violating any safety recommendations and adhering to coding standards (few constructor arguments etc.)?

Is Java Spring really better than straight up Java programming

I have read that dependency injection is good for testing, in that a class can be tested without its dependencies, but the question comes to my mind if Class A depends on Class B or C or any class, testing Class A independent of some class is yielding a test result of zero, not a failed or past test.
Class A was created to do something and if it is not fed anything whether using new key word or setting up the extra files in Spring, Class A won't do any work.
About the idea of making code modular, readable and maintainable: so business classes became cleaner, but all we did was shift confusion from dirty Java business classes to convoluted XML files and having to delete interfaces used to inject to our loosened objects.
In short, it seems we have to make edits and changes to a file somewhere,right?
Please feel free to put me in my place if my understanding is lacking, just a little irritated with learning Spring because I see the same amount of work just rearranged.
Dependency injection is good for unit testing because you can individually test each method without that method depending on anything else. That way each unit test can test exactly one method.
I would say that if the xml is what’s annoying you check out Spring boot. It’s based on a java configuration so no xml and it simplifies a lot of configuration for you based on your class path. When I first started spring I found the xml very daunting coming from a java background but the annotation based configuration and the auto configuring done by spring boot is extremely helpful for quickly getting applications working.
IMO biggest advantage of using the spring is dependency injection which makes your life easy. For example if you would like to create a new service with three dependencies, then you can create a class very easily using Spring. But without spring, you will end up writing different factory methods which will return you the instances you are looking for. This makes your code very verbose with static method calls. You may want to take a look at the code repositories before spring era.
Again if you would like to use Spring or not is your personal call based on project complexity. But it's other features/advantages cant be overlooked.
And XML files or Java configs are the ways of achieving spring configuration - where you would like to add your business logic is personal flavour. Only thing is you should be consistent all across your project.
I would suggest that you read Martin Fowler's great article on Inversion of Control and Dependency Injection to gain a better understanding of why frameworks like Spring can be really useful to solve a well known set of common dependency injection problems when writing software.
As others have mentioned, there is no obligation to use Spring; and whatever you can do with Spring, you can probably do it by other means like abstract factories, factory methods, or service locators.
If your project is small enough, then you probably wouldn't mind solving the dependency injection issues on your own using some design patterns like those mentioned above. However, depending on the size of your project, many would prefer to use a framework or a library that already packs a bunch of solutions to these recurrent head scratchers.
In regards to the advantages of dependency injection frameworks when doing unit testing is the idea that you don't need to test the dependencies of your class, but only your class.
For example, most likely your application has a layered design. It is very common to have a data access class or a repository that you use to retrieve data from a datasource. Logically, you also have a class where you use that DAO.
Evidently, you already wrote unit testing for your DAO, and therefore, when you're testing your business class (where the DAO is being used) you don't care about testing your DAO again.
Fortunately, since Spring requires some form of dependency injection for your DAO, this means your class must provide a constructor or a setter method through which we can inject that DAO into our business class, right?
Well, then during unit testing of your business class, you can conveniently use those injection points to inject your own fake DAO (i.e. a mock object). That way, you can focus on the testing of your business class and forget about retesting the DAO again.
Now compare this idea with other solutions you may have done on your own:
You inject the dependency directly by instantiating the DAO within your business class.
You use a static factory method within your code to gain access to the DAO.
You use a static method from a service locator within your code to gain access to the DAO.
None of these solutions would make your code easy to test because there is no simple manner to get in the way of choosing exactly what dependency I want injected into my business class while testing it (e.g. how do you change the static factory method to use a fake DAO for testing purposes?).
So, in Spring, using XML configuration or annotations, you can easily have different dependencies being injected into your service object based on a number of conditions. For example, you may have some configurations for testing that evidently would be different than those used in production. And if you have a staging environment, you may even have different XML configurations of dependencies for your application depending on whether it is running in production or integration environments.
This pluggability of dependencies is the key winning factor here in my opinion.
So, as I was saying, my suggestion to you is that you first expand your understanding of what problems Spring core (and in general all dependency injection frameworks) is trying to solve and why it matters, and that will give you a broader perspective and understanding of these problems in a way that you could to determine when it is a good idea to use Spring and when it is not.

Difference between Spring IOC and Spring AOP

What is the Difference between Spring IOC and Spring AOP and their Importance ?
Have you searched the web for IoC and AOP? There are a lot of references to both.
In a nutshell, IoC allows an external force to determine what implementation will be used by code rather than the code determining the implementation. The "external force" might be a configuration file, a unit test, other different code, etc.
AOP allows cross-cutting concerns to be implemented outside of the code affected by those concerns.
The "purpose" of Spring includes IoC and AOP, but goes quite a ways beyond that in its scope.
For more details please check.
Inversion of Control Containers and the Dependency Injection pattern and
Aspect-oriented programming
Also check this
What is AOP, Dependency Injection and Inversion Of Control in Simple English
IoC, AOP and more
Spring IOC: In simple answer normally you create object with new operator and set yourself for getter and setter. So, yes we use new operator in Java to create object. There is no any bad in doing this. But, when your project size grows and lots of developers are working, and you want to achieve POJO-based programming, you can use DI. So then maybe your question arises - why I can not code it myself? Of course you can use the power of reflection, annotation, and XML. But, some other had already coded this then why not reuse the third party one? There are lots of options for you to choose; Spring can be the best one. It manages your object life cycle from object creation to its destruction. You use the objects created and set by Spring DI container but you do not create them yourself.
Spring AOP: It is related to cross cutting concern. What it mean is in large system the common functionality is scattered throughout different modules. So AOP provides an easiest way to take out a common implementation in the form of 'aspect'. You can also in this case write own implementation using proxy concept but you can reuse the code of proxy based that is implementation of APO alliance using Spring.
Objective of Spring IOC is to reduce explicit dependencies between components, while purpose of Spring AOP is to wire components together possibly by enforcing certain common behavior (read: NOT Interface)
Since purpose of Spring AOP is to enforce certain behavior across components.So, Spring IOC comes in handy to achieve this purpose

Spring - dependency injection benefits

I'm a newbie to Spring Framework and of course first thing comes to mind about spring is dependency injection. Now i could be wrong since i just started learning about Spring framework (esp. about dependency injection) but i think that dependency injection of beans to said objects is not meant for transaction data. Since the bean definition is for example defined in the spring.xml (a blue print) it is not meant for transactional data but rather for static and small amount of data. I don't see that there's any way to inject thousands of transactional objects into another object using dynamic XML (created during runtime).
So did i get this right? If that is so what's the real benefit of dependency injection?
There are several benefits from using dependency injection containers rather than having components satisfy their own dependencies. Some of these benefits are:
Reduced Dependencies
Reduced Dependency Carrying
More Reusable Code
More Testable Code
More Readable Code
These benefits are explained in more detail here.
You are right, transactional data (eg: data that represents a table row) don't normally be injected declaratively. Spring DI (dependency injection) commonly use to handle collaboration between multiple classes.
Common examples I've seen is along with DAO (data access object) and MVC (model view controller) pattern. In enterprise environment it's common to have a project with dozens or hundreds of database tables -- hence dozens / hundreds of DAO classes which get injected into controller classes.
If you don't use DI, you need to conciously manage which DAO should be created first, and which DAO should be injected into which controller etc. (this is a nightmare)
Code refactoring is (should) be a common thing as well. Business requirement always changes constantly. Without DI one simple refactoring could result in a massive and tricky untangling of 'which class depends on what and where'
Of all the articles I've read about the dependency injection, this is by far the best.
If you are using Spring for DI, I would suggest you read about #primary annotation. Spring makes it even easier to choose the implementation you want(from multiple implementations) for a given service. This article is good.
Dependency Injection and Inversion of Control change the control flow adding to a specific component the responsibility to manage de dependency graph and manage how it will be connected. The result is a great decoupling between dependant and dependency, improving the code maintainability, application reliability, and testability.

Dependency injection, Scala and Spring

I love the concept of DI and loosely coupled system, a lot. However, I found tooling in Spring lacking at best. For example, it's hard to do "refactoring", e.g. to change a name of a bean declared in Spring. I'm new to Spring, so I would be missing something. There is no compiling time check etc.
My question is why do we want to use XML to store the configuration? IMO, the whole idea of Spring (IoC part) is to force certain creational pattern. In the world of gang-of-four patterns, design patterns are informative. Spring (and other DIs) on the other hand, provides very prescribed way how an application should be hooked up with individual components.
I have put Scala in the title as well as I'm learning it. How do you guys think to create a domain language (something like the actor library) for dependency ingestion. Writing the actual injection code in Scala itself, you get all the goodies and tooling that comes with it. Although application developers might as well bypass your framework, I would think it's relatively easy to standard, such as the main web site/app will only load components of certain pattern.
There's a good article on using Scala together with Spring and Hibernate here.
About your question: you actually can use annotations. It has some advantages. XML, in turn, is good beacause you don't need to recompile files, that contain your injection configs.
There is an ongoing debate if Scala needs DI. There are several ways to "do it yourself", but often this easy setup is sufficient:
//the class that needs injection
abstract class Foo {
val injectMe:String
def hello = println("Hello " + injectMe)
}
//The "binding module"
trait Binder {
def createFooInstance:Foo
}
object BinderImpl extends Binder {
trait FooInjector {
val injectMe = "DI!"
}
def createFooInstance:Foo = new Foo with FooInjector
}
//The client
val binder:Binder = getSomehowTheRightBinderImpl //one way would be a ServiceLoader
val foo = binder.createFooInstance
foo.hello
//--> Hello DI!
For other versions, look here for example.
I love the concept of DI and loosely
coupled system, a lot. However, I
found tooling in Spring lacking at
best. For example, it's hard to do
"refactoring", e.g. to change a name
of a bean declared in Spring. I'm new
to Spring, so I would be missing
something. There is no compiling time
check etc.
You need a smarter IDE. IntelliJ from JetBrains allows refactoring, renaming, etc. with full knowledge of your Spring configuration and your classes.
My question is why do we want to use
XML to store the configuration?
Why not? You have to put it somewhere. Now you have a choice: XML or annotations.
IMO,
the whole idea of Spring (IoC part) is
to force certain creational pattern.
In the world of gang-of-four patterns,
design patterns are informative.
ApplicationContext is nothing more than a big object factory/builder. That's a GoF pattern.
Spring (and other DIs) on the other
hand, provides very prescribed way how
an application should be hooked up
with individual components.
GoF is even more prescriptive: You have to build it into objects or externalize it into configuration. Spring externalizes it.
I have put Scala in the title as well
as I'm learning it. How do you guys
think to create a domain language
(something like the actor library) for
dependency ingestion.
You must mean "injection".
Writing the
actual injection code in Scala itself,
you get all the goodies and tooling
that comes with it.
Don't see what that will buy me over and above what Spring gives me now.
Although
application developers might as well
bypass your framework, I would think
it's relatively easy to standard, such
as the main web site/app will only
load components of certain pattern.
Sorry, I'm not buying your idea. I'd rather use Spring.
But there's no reason why you shouldn't try it and see if you can become more successful than Spring. Let us know how you do.
There are different approaches to DI in java, and not all of them are necessarily based on xml.
Spring
Spring provides a complete container implementation and integration with many services (transactions, jndi, persistence, datasources, mvc, scheduling,...) and can actually be better defined using java annotations.
Its popularity stems from the number of services that the platform integrates, other than DI (many people use it as an alternative to Java EE, which is actually following spring path starting from its 5 edition).
XML was the original choice for spring, because it was the de-facto java configuration standard when the framework came to be. Annotations is the popular choice right now.
As a personal aside, conceptually I'm not a huge fan of annotation-based DI, for me it creates a tight coupling of configuration and code, thus defeating the underlying original purpose of DI.
There are other DI implementation around that support alternative configuration declaration: AFAIK Google Guice is one of those allowing for programmatic configuration as well.
DI and Scala
There are alternative solutions for DI in scala, in addition to using the known java frameworks (which as far as I know integrate fairly well).
For me the most interesting that maintain a familiar approach to java is subcut.
It strikes a nice balance between google guice and one of the most well-known DI patterns allowed by the specific design of the scala language: the Cake Pattern. You can find many blog posts and videos about this pattern with a google search.
Another solution available in scala is using the Reader Monad, which is already an established pattern for dynamic configuration in Haskell and is explained fairly well in this video from NE Scala Symposium 2012 and in this video and related slides.
The latter choice goes with the warning that it involves a decent level of familiarity with the concept of Monads in general and in scala, and often aroused some debate around its conceptual complexity and practical usefulness. This related thread on the scala-debate ML can be quite useful to have a better grip on the subject.
i can't really comment on scala, but DI helps enforce loose coupling. It makes refactoring large apps soooo much easier. If you don't like a component, just swap it out. Need another implementation for a particular environment, easy just plug in a new component.
I agree! To me he way most people use Spring is a mild version of hell.
When you look at the standard Springified code there are interfaces everywhere, and you never really know what class is used to implement an interface. You have to look into some fantastic configuration to find that out. Easy read = not. To make this code surfable you need a very advanced IDE, like Intelly J.
How did we end up in this mess? I blame automated unit testing! If you want to connect mocks to each and every class you can not have dependencies. If it wasn't for unit testing we could probable do just as well without loose coupling, since we do not want the customer to replace single classes willy nilly in our Jars.
In Scala you can use patterns, like the "Cake Patten" to implement DI without a framework. You can also use structural typing to do this. The result is still messy compared to the original code.
Personally I think one should consider doing automated testing on modules instead of classes to escape this mess, and use DI to decouple entire modules. This strategy is by definition not unit testing. I think most of the logic lies in the actual connections between classes, so IMHO one will benefit more from module testing than unit testing.
I cannot agree that XML is problem in Java and Spring:
I use Spring and Java extensively without to much XML because most configuration is done with annotations (type and name is powerful contract) - it looks really nice. Only for 10% cases I use XML because it is easier to do it in XML than code special solution with factories / new classes / annotations. This approach was inspired by Guice and Spring from 3.0 implements its as JSR-330 (but even that I use Spring 2.5 with spring factory configured with JSR-330 annotations instead of default spring-specific #Autowired).
Probably scala can provide better syntax for developing in DI style and I'm looking at it now (pointed Cake Pattern).

Resources