Can I use Spring without annotations at all only through xmls? - java

I have a web application using spring annotations extensively. Can I switch back from spring annotations to xml configuration files? Encluding controllers,..etc. I need examples of the configuration files please.

Yes you can switch to externalize the configuration using xml's. Initially only xml's were supported by spring. You can get examples from their reference manual.
If you are looking for complete examples then www.springbyexample.org

Yes. Spring supports annotations, configuration classes and xml configuration. It was never the goal of annotations to deprecate the xml configuration, and it is still fully supported today.
At the S2G forum in Amsterdam last year, it was specifically stated that the goal remains for both approaches to be completely equivalent.
As for the details on how to do it, the documentation of Spring is very good. I suggest you start there. Check out the pet store example, and read up on ContextLoaderListener. It should get you started.

Yes, you can switch back and forth to XML and annotations. In fact, if you even need, you can use a combination of both. Additionally, depending on the type of control you are trying to extract from XML configuration, you can also use #Configuration annotations which provides a way of producing XML configuration via Java code. Keep in mind, however, that there are a few obscure configuration constructs that are not representable by any annotations and can only be done via XML files.

Related

Why Java Config is favorable in spring boot when compared to XML config?

I am new to spring-boot. I am building a rest based application using spring-boot and was working on setting up security using spring-security. It is my understnading that I can setup spring-security with either xml config or with Java config.
However, I found the following in spring-boot documentation. https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-configuration-classes.html
It is in favor of using Java Config as opposed to XML config. Changes in Java config requires recompilation. Yet, it makes me think why the documentation favors Java Config.
Configuration classes Spring Boot favors Java-based configuration. Although it is possible to call SpringApplication.run() with an XML
source, we generally recommend that your primary source is a
#Configuration class. Usually the class that defines the main method
is also a good candidate as the primary #Configuration.
Many Spring configuration examples have been published on the Internet
that use XML configuration. Always try to use the equivalent
Java-based configuration if possible. Searching for Enable*
annotations can be a good starting point.
15.1 Importing additional configuration classes You don’t need to put all your #Configuration into a single class. The #Import annotation
can be used to import additional configuration classes. Alternatively,
you can use #ComponentScan to automatically pick up all Spring
components, including #Configuration classes.
15.2 Importing XML configuration If you absolutely must use XML based configuration, we recommend that you still start with a #Configuration
class. You can then use an additional #ImportResource annotation to
load XML configuration files.
There are some advantages
Java is type safe. Compiler will report issues if you are configuring right bean class qualifiers.
XML based on configuration can quickly grow big. [Yes we can split and import but still
Search is much simpler, refactoring will be bliss. Finding a bean definition will be far easier.
There are still people who like XML configuration and continue to do it.
For more info you can refer Java configuration advantages Some more reasons

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?

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.

Transaction configuration for Spring Java configured context

I've been struggling with this for a few hours now.
I'm trying to migrate my Spring XML configuration to a full Java based configuration.
I'm using AnnotationConfigApplicationContext as a context implementation.
I'm having trouble finding an Java equivalent for this line, from my old XML configuration:
<tx:annotation-driven transaction-manager="transactionManager" />
As a result, Spring doesn't manage the transactions.
In my Java configuration I have initialized the relevant beans for transactions: the session factory, the transactional manager, etc, but without that line, no transaction proxy is used, so no transactions are actually in place.
So my question is how do I either translate that line to my Java context configuration or how to I go about solving the problem in another way.
Any help is appreciated.
Thanks.
You can now use #EnableTransactionManagement.
See: http://blog.springsource.com/2011/06/10/spring-3-1-m2-configuration-enhancements/
In my experience, it's not practical to entirely replace the XML config with #Bean-style config. Some things do make more sense configured in java, specifically your own bean definitions. But when it comes to infrastructural-type declarations like <tx:annotation-driven>, the XML syntax is a lot more concise.
You can reproduce the same effect in pure java, but it ends up being cumbersome and unintuitive, since things like <tx:annotation-driven> are typically interactions of complex low-level Spring infrastructure classes that you really don't want to touch.
My advice - mix and match, using each of Java and XML for their own strengths. This is quite easy to do. I prefer to keep the normal XML ApplicationContext classes, and then declare my #Configuration classes as beans in that XML context, alongside things like <tx:annotation-driven>.
Take a look at https://spring.io/blog/2011/02/17/spring-3-1-m1-introducing-featurespecification-support. Spring 3.1's FeatureSpecification classes such as TxAnnotationDriven are designed to solve exactly the problem described above.

java annotations: library to override annotations with xml files

Java has annotations and that is good. However, some developers feel that it is best to annotate code with metadata using xml files - others prefer annotations but would use metadata to override annotations in source code.
I am writing a Java framework that uses annotations. The question is: is there a standard way to define and parse metadata from xml files. I think this is something every framework that uses annotations could benefit from but I can seem to find something like this on the Internet.
Must I roll my own xml parsing/validation or has someone already done something like this?
There is not a standard way, but here are some Java frameworks who does it:
JPA - check ejb-3_0-fr-spec-persistence.pdf
Spring Framework
TestNG - as written above, though I think it focuses to much on the annotation side rather than the actual configuration he tries to achieve
Seam Framework
I wrote the Annox library which does exactly what you need. With Annox you can read arbitrary annotations from XML.
It's not exactly what you want, but the backport175 project has an implementation of annotations for Java versions before Java 5.
It has some of the functionality you search in that it will read both its own style implementations and "real" annotations if they are present. Maybe this can be used as a starting point to build a more general framework.
Use JAXB http://java.sun.com/developer/technicalArticles/WebServices/jaxb/
You would write the xsd for your metadata file, generate JAXB classes that can help you parse the xml files.

Categories

Resources