Java spring what is the point of XML programming? - java

I'm going through the Spring right now and have some things on my mind. What is the point of doing so many things in the XML files? I've been through searching for the answer for this but found nothing interesting. I mean all those denpendency injections and declaring objects present way much better when written in Java, don't they? XML is not intuitive and there's aparently more code to write and I'm in the very beginning of my Spring path but I don't feel like this can be useful in the future... Can somebody explain to me what is so good about bringing programming to the XML? Or maybe pass me the link of some article which may help me? Thanks!

This is a complaint that comes from everyone who starts in Spring. It was way worse back in the 1.0 days. I have been doing XML configs in Spring and Struts for many years and have converted most if not all of my code to the new Spring annotated #Configuration and Springboot.
1) If you are new to Spring use Spring STS(Eclipse as your IDE) http://spring.io/tools ->Spring tool Suite.
2) Springboot - Remember that the whole idea behind Springboot is to get rid of all of what you are complaining about. Nearly all the configuration is done without XML.
3) Maven - The only real file you will need in XML is the POM.xml for your dependencies but Spring STS has a wrapper interface that will help you add dependencies as you go.
4) Pivital TC- When you start Spring STS you will notice it comes with Pivital's version of Tomcat.
5) File -> New-> Spring Starter Project: Select Web and Thymleaf(JSP replacement) I have lost my desire to code in JSP.
You will notice the DemoApplication.java class
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Notice that everything is now done without XML. The ApplicationContext.XM is now a simple Java class.
Springboot has a bunch of great new annotations that will take all the XML way :)
If there is something specific you want to do just add it in the comments below and I can guide you further. Thymeleaf is pretty simple you just add your HTML files in the /demo/src/main/resources/templates directory.
Good luck! Don't give up Spring is very powerful.

You have to look at the history behind the introduction of the Spring Framework as a better programming model than EJB2.x at the time it was introduced to understand where it is today. However, EE5, 6 and 7 have now changed radically to improve developer productivity, more convention over configuration, and use of annotations to indicate behavior of POJO classes.
Although Spring has been moving away from XML based configuration for a while and also using more annotations, you have to ask yourself at this point whether you'd rather Spring's implementation of JSR250 (Common Annotations) and JSR330 (Dependency Injection), or EE6 and 7, since both implement the same specs. There will probably be many heated replies to this point of view, but you have to take a good look at what it is you're trying to do before deciding on one verses the other. If you're planning on deploying a Spring based app to an EE6+ app server, then a pure EE solution might be the simplest and easiest approach.

I think ideally you wouldn't be programming in XML. In the end, it's not a programming language but a markup language.
I guess people use it because a markup language can be read and understood even by a person without a technical background, and also because processing an XML file is cheaper than calling the Java engine and using that in applications.

Related

Spring Dependency Injection vs. Writing to Interfaces

I have a few questions about Spring paradigm in Java:
1) Suppose I have an application where I write everything to interfaces, and then at the very last moment, somewhere in my actual main() or maybe in a config file, I define my specific classes to be used. Have I achieved the same objective as Spring? In that case, why do I need Spring's DI? Writing to interfaces, and leaving specifics till the very last moment, is standard practice that programmers have been using for decades.
2) If the objection is to new'ing objects at some (final) point in time, this has to be done at some point in my interface-driven app, but what's wrong with that? How does having a "new" statement make a class unusable or untestable - or is it just readability/transparency?
3) People say that declaratively using objects "gets rid of dependencies." But we still have a dependency: we have to import a new class, even if we don't "new" it, before we can compile the code?
Some people, like me, prefer to configure the wiring of dependencies and interface implementations using Spring XML rather than hardcode them. All the wirings are in one place (assuming you are not using annotations) and I can also argue that modifying the configuration of the XML file is easier than modifying code. You can also tweak the Spring file between runs of your application if there is something that needs to change.
Spring is a good framework that has been around for a while. I find it's really really good at Dependency Injection (DI). While there is nothing "wrong" with your approach in #1, I think using Spring will give you a more robust implementation. Why reinvent the wheel?

Why Spring MVC configuration support for XML configuration is deprecated?

Spring MVC uses mainly annotations to configure its Controllers, as far as I know, the only way to configure a Controller in Spring WITHOUT Annotions (only XML) is extending the AbstracController (or Similar Controller classes) and currently all this classes are deprecated for Spring 3.
While I think that is a good idea to drop support for this classes, mainly because extending this classes creates controllers that hardly depend of Spring as a dependency, I don't understand why Spring doesn't provides a configuration like Struts Actions (Actions in Struts 2 don't extend any weird class so they dont' have any dependency of Struts)
Why Spring MVC doesnt provide a clean POJO-style configuration like Struts 2 Actions via XML?
Why to drop support for XML configuration on MVC using ugly Annotations? why not to drop it in ALL Spring Proyects?
The main problem with the XML/POJO approach is that there is no way to tell from looking at your code that special magic is going on.
Instead of seeing
#SomeAnnotation <<-- Oh, golly there is something special happening here.
java code...
You see
Java code <<-- special magic hidden in XML file (or not, no way to tell)
<<-- are these linked? no idea..
<<-- is something going on? let me go and search....
If changes happen to the source code, the XML may (or may not be) out of sync.
With the annotations you can update the java code and the spring annotations at the same time.
Yes it's cluttered but at least it's easy to sync the two.
Annotations are hard enough to grok when they're in your face. If they're not even visible the mental burden for us non-angry developers is really too much to bear.
why not to drop it in ALL Spring Projects?
Wouldn't that be sweet....
using ugly Annotations?
Obviously the question has been asked: Is there a way to hide annotations in Eclipse?
And the answer is: https://stackoverflow.com/a/2569646/650492
Sort of... does that help?

creating reusable modules

I'm writing a big Red5 Java application for the web.
Red5 a Flash Media Server alternative that is java based and is written with the spring framework.
I want to have many versions of my application online, each with different behaviors and different classes enabled or disabled.
I'm looking for a way to convert my code into modules based code that will allow me to remove/add modules/features from the main application.
I know about OSGI http://www.springsource.org/osgi but it says that it needs a SpringSource dm server and I have no idea how it's gonna work together in red5 and it's seems very complicated to fully understand.
I don't have a good knowledge of spring framework in general, i work with it db-related and that's it. red5 uses it more extensively.
so can anyone please make any sense from this information ? is there something that can be done to divide my code to modules ?
any information regarding the issue would be greatly appreciated.
My preferred method of dealing with this kind of situation is Dependancy Injection (DI). Spring has a DI capability built in, for which a tutorial is easy to find online. However, Spring's DI is not as good, for many reasons, as that provided by Guice, which I would highly recommend. (The main advantage of Guice over Spring's DI in my opinion is type safety.)
DI is basically a mechanism for replacing class implementations at runtime. Rather than hard code dependancies into classes (by having a class construct other classes directly for example) you code them to have their dependant classes passed to them in their constructors. The DI framework will then pass the correct instances at runtime according to the configuration. Spring configuration can be done via annotations or an XML file, Guice uses a subclass of com.google.inject.AbstractModule.
So you could use different configuration files for the different instances of your application, and have them provide different sets of features for activation, or indeed different implementations of the same feature. If you set up the application to use this technique then the only thing that need differ between instances is a single configuration file.

Spring annotation-based DI vs xml configuration?

Recently in our team we started discussing using spring annotations in code to define spring dependencies. Currently we are using context.xml to define our dependencies. Would you give me some clues for either approach, and when one is better to be used?
Edit: I know this seems a duplicate question to a more-general one, but I am interested in the impacts of annotations vs configuration for dependency injection only, which I believe would have different answers and attitude than the general question.
After reading some related posts here and having further discussion in the team we come to the following conclusions. I hope the would be useful to others here.
About XML configuration (which we are using up to now), we decided to keep it for dependencies defined by libraries (regardless if being developed by us, or by third parties).
Libraries, by definition, provide a particular functionality and can be used in various scenarios, not necessarily involving DI. Therefore, using annotations in the library projects we develop ourselves, would create a dependency of the DI framework (Spring in our case) to the library, making the library unusable in non-DI context. Having extra dependencies is not considered a good practice among our team (an in general IMHO).
When we are assembling an application, the application context would define the necessary dependencies. This will simplify dependency tracking as the application becomes the central unit of combining all the referenced components, and usually this is indeed where all the wiring up should happen.
XML is also good for us when providing mock implementations for many components, without recompiling the application modules that will use them. This gives us flexibility when testing running in local or production environment.
In regards to annotations, we decided that we can benefit using them when the injected components will not vary -- for instance only a certain implementation for a component will be used troughout the application.
The annotations will be very useful for small components/applications that will not change or support different implementations of a dependency at once, and that are unlikely to be composed in a different way (for instance using different dependencies for different builds). Simple micro-services would fit in this category.
Small enough components, made up with annotations, can be used right out of the box in different projects, without having the respective applications to cover them in their XML configuration. This would simplify the application dependency wiring for the application and reduce repetitive setups.
However, we agreed that such components should have the dependencies well described in our technical documentation, so that when assembling the entire application, one can have an idea of these dependencies without scrolling through the code, or even loading the module in the IDE.
A negative side effect of annotation-configured components, is that different components could bring clashing transitive dependencies, and again it is up to the final application to resolve the conflicts. When these dependencies are not defined in XML, the conflict resolution approaches become quite limited and straying far from the best practices, if they are at all possible.
So, when going with annotations, the component has to be mature enough about what dependencies it is going use.
In general if our dependencies may vary for different scenarios, or a module can be used with different components, we decided to stick to XML. Clearly, there MUST be a right balance between both approaches, and a clear idea for the usages.
An important update regarding the mixed approach. Recently we had a case with a test framework we created for our QA team, which required dependencies from another project. The framework was designed to use the annotation approach and Spring configuration classes, while the referenced project had some xml contexts that we needed to reference. Unfortunately, the test classes (where we used org.testng with spring support) could only work with either the xml or java configuration classes, not mixing both.
This situation illustrates a case where mixing the approaches would clash and clearly, one must be discarded. In our case, we migrated the test framework to use spring xml contexts, but other uses could imply the other way around.
Some advantages of using XML configuration:
The XML configuration is at one place, instead of being scattered all over the source code in case of annotations. Some people may argue that IDEs like STS allow you to look at all annotations based configuration in one place, but I never like having dependencies on IDEs.
Its takes a little more efforts to write XML config, but it saves a lot of time later when you search for dependencies and try to understand the project.
XML keeps configuration well organized and simple. Hence is easier to understand, it helps new relatively inexperienced team members get up to speed quickly.
Allows you to change the config without a need to recompile and redeploy code. So it is better, when it comes to production support.
So in short XML configuration takes a little more efforts, but it saves you a lot of time & headache later in big projects.
2.5 years later:
We use annotations mostly these days, but most crucial change is that we create many small projects (instead of a one big project). Hence understanding dependencies is not a problem anymore; as each project has it's unique purpose and relatively small codebase.
from my experience, I would prefer(or rather am forced by limitations) to use a combination of XML and annotation based DI . If I need to inject a Map of elements inside a bean , I would have to define a util:map and autowire it . Also, I need to use XML DI to inject datasource into the sessionFactory if I have multiple datasources and so on . So a combination of both would be requited .
I prefer the usage of component-scan to autodetect the services and Dao . This cuts down a lot of Configuration (We cut down the configuration files by around 50% switching to component-scan). Annotation based DI supports both byName(#Resource) and byType(#Autowired).
In short my advice to be to go for a fixture of both . I feel that more annotation support will definitely be on cards in future Spring releases.
Take a look at this answer here: Xml configuration versus Annotation based configuration
A short quote directly from there:
Annotations have their use, but they are not the one silver bullet to
kill XML configuration. I recommend mixing the two!
For instance, if using Spring, it is entirely intuitive to use XML for
the dependency injection portion of your application. This gets the
code's dependencies away from the code which will be using it, by
contrast, using some sort of annotation in the code that needs the
dependencies makes the code aware of this automatic configuration.
However, instead of using XML for transactional management, marking a
method as transactional with an annotation makes perfect sense, since
this is information a programmer would probably wish to know.
EDIT: Also, take a look at the answers here: Java Dependency injection: XML or annotations They most probably target the area of your interest much better.
From my own experience annotations better than xml configuration. I think in any case you can override xmls and use annotations. Also Spring 4 give us a huge support for annotations, we can override security from xml to annotations e.t.c, so we will have not 100 lines xml but 10 lines Java Code.
Are annotations better than XML for configuring Spring?
The introduction of annotation-based configurations raised the
question of whether this approach is 'better' than XML. The short
answer is it depends. The long answer is that each approach has its
pros and cons, and usually it is up to the developer to decide which
strategy suits them better. Due to the way they are defined,
annotations provide a lot of context in their declaration, leading to
shorter and more concise configuration. However, XML excels at wiring
up components without
touching their source code or recompiling them. Some developers prefer
having the wiring close to the source while others argue that
annotated classes are no longer POJOs and, furthermore, that the
configuration becomes decentralized and harder to control.
No matter the choice, Spring can accommodate both styles and even mix
them together. It’s worth pointing out that through its JavaConfig
option, Spring allows annotations to be used in a non- invasive way,
without touching the target components source code and that in terms
of tooling, all configuration styles are supported by the Spring Tool
Suite.
my personal option is that xml is better since you have all at one place and you do not need to deep into your packages to search the class.
We can not tell which method is good, it depends on your project. We can nither avoid xml nor annotation. One advantage of using xml is that we can understand the project structure just seeing the xml context files, but annotation reduces lots of meta configuration. So I prefer 30% xml and 70% annotation.
By using XML, you prevent code from being polluted with framework-specific annotations and thus creating an undesired coupling. Keep the framework at the application boundary so you can always replace it should the need arise.
Frameworks come and go, but many applications live for decades. Fortunately, Spring is a non-invasive framework and doesn't bend your architecture. Keeping the configuration in XML will make it even more detached from your application.
Remark: in order to benefit from all this, your application should be well-designed in the first place.

Spring 3 Annotations

I can't get spring annotations to work at all, I'm just trying to get the simplest thing to work...
.../mycontext/something -> invokes method:
#RequestMapping(value = "/something")
#ResponseBody
public String helloWorld() {
System.out.println("hello world");
return "Hello World";
}
My main problem is no matter how hard I try, I can't find a complete SIMPLE example of the configuration files needed, every spring tutorial is filled with junk, I just one one controller to handle a request with a mapping and can't get it to work
does anyone know of a simple and complete spring example. pet-clinic is no good, it's way too complicated, I have a tiny basic use case and it's proving to be a real pain to get working (this always happens with Spring)
You should try Spring Roo. It will generate a simple Spring application for you using simple commands and then you can incrementally extend it. It is a great tool for learning Spring as well as for rapid application development.
You can also find several examples of Spring 3.0 MVC framework.
the absolute simplest alternative if you're familiar with Eclipse is to use SpringSource Tool Suite (Eclipse plugins)
This product has a tcServer bundled inside.
By default, STS will start with "dashboard" page in the editor window. From here, you can click on creating a controller as demonstrated by this screenshot:
This is a quite simple controller and all you have to do to get it deployed on the bundled tcServer (Tomcat with some extra management features) is to click "next" a few times in the wizard.
That's a very good starting point for doing your own testing!
I endorse this blog post,Layered architecture with Hibernate and Spring. It was a great help for me when I tried to move from the declared xml approach to annotations. It contains the usages of annotations in Entity, Dao and Service layers.
I'd recommend you checkout some of projects from here
and try going trough book spring in action(manning) they give very good example on how to use aspects
or refer to this question

Categories

Resources