I'm studying about Java Servlet and I'm curious why Apache Software foundation got rid of web.xml and made the programmers use annotation. Is using annotation better than using web.xml? What are the differences between them?
There is no difference, annotations are just more convenient and prevents you from having bloated web.xml with hundreds of entries (in case of bigger application). It is also a part of Convention over configuration approach. Also note that you don't have to use annotations, you can still register your servlets in web.xml.
There are benefits and drawbacks to using both XML and annotation based Spring configuration files. However, it doesn't have to be an 'either-or' type of decision.
There is a wider issue here, that of XML vs Annotation If your object model is only ever going to persisted in one way, then inlined meta-data (i.e. annotations) are more compact and readable.
If, however, your object model was reused in different applications in such a way that each application wanted to persist the model in different ways, then externalising the meta-data (i.e. XML descriptors) becomes more appropriate.
Neither one is better, and so both are supported, although annotations are more fashionable. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.
Related
I'm new to Spring and DI in general. But from what I have read, DI affords you the ability to swap out implementations very easily using frameworks like Spring. I can understand value there when it comes to XML bean configuration because code doesn't need to be changed at all for accomplishing switchable implementations. But if we're using annotations like #Autowired or #Qualifier...we would need to change the code. So why do we want to use annotations over XML-based configuration?
This was actually a topic of lively conversation around the time that Spring 3.0 came out in 2009 and JavaConfig was added to the core system base.
In theory, being able to externalize application setup is a great thing. However, it turns out that in practice there are two distinct groups of setup choices: the application shape or dependency graph, and particular values like API keys, database connection strings, and so on that vary between environment but usually don't change the way that the beans are wired.
Experience has shown that the dependency graph, which is essentially what you'd express in XML, is almost never changed without also making changes to the accompanying implementation code anyway, so there is very little real-world benefit to defining the graph in XML. On the other hand, writing #Bean methods in Java means that it's a lot easier to test configuration when needed, the compiler can ensure type safety, and decision logic (such as conditionals) are simpler to implement.
Furthermore, the availability of annotations means that it's possible to extend the domain-specific language for configuration fairly easily in Java--just create a new annotation and its accompanying processor (such as #ConditionalOnProperty); Spring Boot itself is an extreme example of the flexibility of this model. In XML, on the other hand, injecting new tags or attributes into a schema is a lot more of a hassle.
There are times when XML may still be the better choice (I've particularly gone with it for writing out Spring Integration pipelines, which can be easier to read in XML than in the Java DSL), but the real-world benefits turned out not to be all that valuable in most cases, and the safety and flexibility of configuration as code has won out.
This is not must, you have to choices to use Annotations or XML its up to you but Annotations is easy to use, faster and more readable than configurations, and when you use it you will find all the information in a single file, but it also have disadvantages.
Annotations preferable
Use Annotations in anything that is stable and defines the core
structure of the application. Anything that would need a code change
is okay to sit as an annotation.
I recommended you to read the following links for more info :
xml-configuration-versus-annotation-based-configuration
spring-framework-xml-vs-annotations
I'm writing an application with Spring MVC which I'd like to be configurable with properties files. I looked into Spring's util namespace and found this:
<util:properties id="MyProperties" location="propertiesPath" />
with this, I can annotate my classes field simply with
#Value("myProperty")
and have the property simply injected. So, it's very simple to read your properties. But when you have to save them, it's not as intuitive.
I've stumbled upon quite a few questions on how to do it properly and I think this represents best what I want to say: Updating a properties file injected by Spring to include a last run timestamp.
My question is: why it's so difficult to save properties in Spring? Am I doing it the wrong way? At this point I am even wondering if saving properties this way is a good practice or if I should use a database.
From Oracle I can read:
The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream.
But Spring seems to make easier only one of them. Please enlighten me.
Thank you.
Spring is largely involved in creating the static, unchanging, structure of your application, and not really involved in transaction processing or business-logic. Often it defines how transactions are to be processed, but it isn't usually involved in the processing itself. We often talk about the separation of the domain model and the architecture -- spring is about architecture.
Writing something out to a store of some kind, say properties to a disk file, is transactional logic (even if you don't need an explicit transaction to do it). It would be one of the end-user features of your system, not part of the architecture -- it would be a feature (even if the end user, in this case, is a sys-admin). Spring has little support for this type of behaviour -- just as it has little support for storing information regarding dynamic changes to the application context.
Using properties like this supposed it read-only. If you need some managing with it, you should better write you custom service with pure java properties handling http://www.mkyong.com/java/java-properties-file-examples/
I am recently back in Javaland from Ruby and Activerecord and was wondering if there were any database solutions that do not require me to set up XML files to use them, and if possible supply any configuration in pure Java?
If you like ActiveRecords in Ruby, you might be interested in jOOQ (Java Object Oriented Querying, a database abstraction library that I wrote). jOOQ requires only little configuration for its source code generator. Your database schema is mapped 1:1 to Java classes, which can then be used in a fluent API very similar to SQL itself.
Also, jOOQ doesn't manage transactions, sessions, caches, etc like JPA or Hibernate might do. So there is no additional runtime configuration required.
http://www.jooq.org
You can configure Hibernate without using any XML via the Configuration class (it doesn't have to read XML documents). It's easier to avoid the mapping of .hbm.xml files if you're using annotated classes and AnnotationConfiguration instead.
See this for more details: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-programmatic
There are many. Though hibernate is the most famous one. It has annotation for most of the configuration and that too is not required, if you use naming strategies.
http://www.hibernate.org/
Greetings,
I have a complicated scenario to handle. I have a wsdl file which uses a particular XML schema.
The XML schema is actually a handcrafted implementation of a specification. There is also a Java based implementation of the same specification. So the XSD used in WSDL and Java classes at hand are quite similar, but not exactly same.
Almost all web service stacks allow creating classes from WSDL or creating WSDL from Java class annotations.
What I want to do, is to use the WSDL and bind XSD used in the wsdl to existing java classes.
Should/can I do this by manually replacing generated Java classes with existing ones? Is it a matter of changing type names in config files and moving binding annotations to existing classes?
If you know any best practices, or java web service stacks that support this kind if flexibility in a practical way, your response would be much appreciated.
Best Regards
Seref
I suggest Spring's Web Services module, which has no code generation involved, but provides a clean separation of concerns. Different concerns are broken out nicely by allowing you to provide your WSDL and existing schema(s) on one side (contract first), your existing Java-based domain model on the other, and a way to plugin in your OXM (Object-XML Mapping) technology of choice.
Since you have hand-crafted WSDL/schema and hand-crafted Java classes, the real work will be in configuring your OXM. I prefer JiBX as it keeps the concerns separated (no XML annotation garbage mixed into your domain) with JAXB as a backup if the learning curve looks too steep. Spring Web Services supports several other OXM frameworks, and you can even use several different ones at once.
As far as best-practices, I consider hand-crafted code a best practice, though I may be in the minority. If you generate classes from XML you end up with classes that are simple data containers with no behavior (assuming you want to regenerate them whenever your WSDL/XSD changes). This is bad if you favor the object-oriented paradigm because you end up having to place your "business logic" in utilities/helpers/services etc. instead of in the domain objects where it really belongs. This is one reason I favor JiBX. I can make very nice OO objects with behavior, a nice clean schema that doesn't necessarily match the objects, and can manage changes to either side with a mapping file similar to how hibernate does it for ORM (Object-Relational Mapping). You can do the same with JAXB, but that requires embedding XML structure into your object model, and binds a single XML representation to it (whereas with JiBX you can have many).
MOXY (I'm the tech lead) was designed for instances where you have an existing XML Schema and an exsting object model. It accomplishes this through XPath based mapping and can ever handle cases where the models are not that similar:
parse google geocode with xstream
MOXy also has an external binding file:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/EclipseLink-OXM.XML
MOXy is a JAXB implementation with extensions (A couple of which are mentioned above). IF you go ahead with Spring, MOXy is configured as a JAXB implementation, and you need to add a jaxb.properties file in with your model classes with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
When I look at Java frameworks like Hibernate, JPA, or Spring, I usually have the possibility to make my configuration via an xml-file or put annotations directly in my classes.
I am cosistently asking myself what way should I go.
When I use annotations, I have the class and its configuration together but with an xml I get a bigger picture of my system because I can see all class-configurations.
Annotations also get compiled in some way I guess and it should be quicker than parsing the xml, but on the other hand, if I want to change my configuration I have to recompile it instead of just changing the xml file (which might become even more handy for production environments on customer side).
So, when looking at my points, I tend to go the xml-way. But when looking at forums or tutorials usually annotations are used.
What are your pros and cons?
A good rule of thumb: anything you can see yourself wanting to change without a full redeploy (e.g. tweaking performance parameters) should really go in something "soft-configurable" such as an XML file. Anything which is never realistically going to change - or only in the sort of situation where you'll be having to change the code anyway - can reasonably be in an annotation.
Ignore any ideas of performance differences between annotations and XML - unless your configuration is absolutely massive the difference will be insignificant.
Concentrate on flexibility and readability.
If you're writing an API, then a word of warning: Annotations can leak out into your public interface which can be unbelievably infuriating.
I'm currently working with APIs where the API vendor has peppered his implementation with Spring MBean annotations, which suddenly means I have a dependency upon the Spring libraries, despite the possibility I might not need to use Spring at all :(
(Of course, if your API was an extension to Spring itself, this might be a valid assumption.)
I think the decision comes down to 'lifecycle', and impedance mismatch between lifecycles.
Lifecycle: Every piece of data, whether its source code, a database row, a compiled class, an object, has a lifecycle associated with it. When does it come into existence and when is it garbage collected?
Suppose I put Hibernate annotations on a Java class. Seems like a reasonable idea, especially if I am creating a new database from scratch and am confident that only this one application will ever connect to it - the lifecycles of my classes, the database schema and the ORM mapping are naturally in sync.
Now suppose I want to use that same class in an API and give it to some third party to consume. The Hibernate annotations leak into my API. This happens because the lifecycle of that class and the database are not the same thing. So we end up using mapping tools to translate between layers of beans in a system.
I try to think about lifecycles and that annotations that can cause lifecycle mismatches should be avoided. Some annotations are relatively harmless in this respect, and some are a hidden danger.
Examples of bad annotations: ORM mapping, database configuration, hard coded config for items that may vary between deployment environments, validations that may vary depending on context.
Examples of harmless annotations: REST endpoint definitions, JSON/XML serialization, validations that always apply.