why spring AOP use JDK Dynamic proxy? - proxy

I know Spring AOP use JDK dynamic proxy and CGLIB.
when target implents Interface -> JDK dynamic proxy
else -> CGLIB.
As you can see why there was this reason in the past version, CGLIB currently has all its shortcomings secured, and in terms of performance, it is superior to the JDK method.
Why would you still use the JDK for the target that implements the interface though? Making all the targets CGLIB seems to have more advantages.

Converting my comments into an answer...
User R.G said:
This SO Q&A provides a lot of insights on the topic.
The accepted answer is not very helpful, but Rafael's comment under his own answer explains it: "Cglib is an external dependeny (...) Relying on third-party software is always a gamble, so it is best when as few people as possible rely on it." I.e., if you have a Spring application with very clean design, always programming against interfaces instead of directly against classes, you do not need CGLIB at all.
Slightly off-topic, but FYI: For similar reasons, the Spock testing framework supports JDK interface proxies out of the box for users who only need interface mocks. In that case, the optional dependency CGLIB (or ByteBuddy) and special stuff like Objenesis are unnecessary. So, this kind of strategy is quite common.

Related

Why have coding over configuration at all?

When we talk about spring (which ever module say jdbc), one of the reasons we use it is because it enables dependency injection and controls lifecycle of beans/classes. In programming, one of the most important fundamental is to code for interfaces rather than implementations, so today if I am using sql server driver v1, I can change it to v2 tomorrow if my code is written in such a way that it cares about Driver interface and not the implementations, then in what case would I ever need coding over configuration ?
The wording of your question seems a bit strange to me. Perhaps you are asking if there are any drawbacks to using Spring-like dependency injection. I can think of a few drawbacks, but whether these drawbacks outweigh the potential benefits of Spring is a matter of opinion.
Unfortunately, a Spring XML file is much more verbose than code to achieve similar (but hard-coded) initialisation of objects.
A programmer has to look not just at code but also at a Spring XML file to figure out what is going on. This, arguably, is a form of the Yo-yo problem.
One significant benefit of Spring is that it can be used to instantiate and configure any Java class (assuming the classes provide getters and setters). In particular, Java classes do not need to be polluted with the need to inherit from framework infrastructure classes. If you don't mind polluting classes with the need to inherit from framework infrastructure, then it is possible to have much more concise configuration files for instantiating and configuring objects. A case study illustrating this idea can be found in Chapters 9, 10 and 11 of the Config4* Practical Usage Guide. I am not proposing that the approach used in that case study be used for all applications, but I think it is a good approach to use when there is a complex, standardised API (such as for JMS) that is implemented by multiple products. In the case study, the approach results in a significantly easier-to-use API and eliminates some potential bugs from applications. Spring doesn't offer such benefits.
Section 9.4.2 of the Config4* Practical Usage Guide outlines a 9-step initialisation process for typical JMS applications. The framework library discussed in the case study ensures that those 9 steps are carried out in the correct order. It has been years since I looked at Spring so I might be wrong, but I don't think Spring has the flexibility to (easily or perhaps at all) enforce such a complex 9-step initialisation mechanism.

What are the principles that make Spring beneficial? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I don't get the benefit of using Spring instead of just using regular Java EE, and I think the reason is I don't have a good grasp of some of benefits of the design principles that Spring employs (dependency injection, etc.).
For example I don't understand what benefits we get by adding #Bean, #Component #Autowired and #Repository annotations.
My question is not what do those annotations do, the question is more what are the principles that Spring makes the implementation of easier or more effective?
Dependency injection is a fantastic pattern. It often allows you to easily unit test components that would otherwise require complicated mocking or stubbing.
It's worth stating that it's possible to use dependency injection without handing the object lifecycle and "wiring" over to a container. I always use dependency injection. However I would only consider using a dependency injection framework for a large project. For instance, last year I wrote a ~2k line webserver in Java and chose not to use "managed" dependency injection. My team agreed that this arrangement provided all the architectural benefits of dependency injection without the drawbacks of a DI framework (bloat, boilerplate, reflection, etc). However if it was 200k lines I may have made a different choice.
Since you're asking about the benefits of Spring and not DI/IoC in general, I have to say that I think Spring is poorly designed. The history of Spring goes hand in hand with the history of antipatterns and bad abstractions that have plagued the Enterprise Java community. To be fair, engineers that I respect have told me that Spring Boot is better. Certainly try it out, you will gain perspective on what does or doesn't work. But maybe also consider other options that adhere to the UNIX philosophy by focusing just on dependency injection.
Spring makes it easy to create Java enterprise applications. It
provides everything you need to embrace the Java language in an
enterprise environment, with support for Groovy and Kotlin as
alternative languages on the JVM, and with the flexibility to create
many kinds of architectures depending on an application’s needs. As of
Spring Framework 5.0, Spring requires JDK 8+ (Java SE 8+) and provides
out-of-the-box support for JDK 9 already.
Read the manual:
https://docs.spring.io/spring/docs/5.1.4.BUILD-SNAPSHOT/spring-framework-reference/
There are tons of useful information.
My question is not what do those annotations do, the question is more
what are the principles that Spring makes the implementation of easier
or more effective?
IoC container, many projects and integrations, Spring Boot with the embedded servlet container. Many built-in features.

Frameworks and specification for JPA, CDI and JSF

I have read and I have understood that JPA, JSF, CDI are only specifications. Such as:
JPA - [Hibernate, Toplink], JSR-000338
CDI - [Spring - Google Guice, PicoContainer], JSR299
JSF - [Primefaces, IceFaces, RichFaces], JSR-000314
So, if they are only specification in a paper, why the packages says, "javax.persistence...", “javax.faces."?
I think that Oracle says: Here is this paper where are the rules. If you want to implement it you must to use my package name ("javax.persistence...", " javax.faces."), and as pay, you can add more features and you will can to put your own package for the extended features?
Other thing, if I study the specifications (jpa, cdi, jsf), Will I be able to use whatever framework? Or even, to construct my software without them?
Please explain me that.
Best regards.
First of all, neither Spring, nor Guice (and not PicoContainer either, AFAIK) are CDI implementations. JBoss Weld is a CDI implementation.
Second. The specification is not just a paper. It's also a set of interfaces and classes that every implementation must correctly implement or extend or which even contain core functionalities that don't depend on the implementation (see Persistence, for example). Those interfaces and classes are the ones that are in the javax package. They're part of the specification itself, and implementations may not modify them.
The idea of a standard is indeed that by relying on the rules described in the specifications, you should be able to use whatever framework implementing the specifications. Beware, though, that some parts are sometimes left unspecified, and that implementations, even without bugs, can do some things differently.
Implementing your software without an implementation would, theoretically, be possible, as long as the user of your software chooses the implementation it wants. But that is extremely unrealistic: you will have to test your software and thus choose an implementation for your tests. And if you plan on supporting several implementations of the specification, you will have to test your software wilth all of them, and even probably need to make adjustments.

Spring annotations basic question

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.

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