is it possible to write a "maven plugin" or something like that which changes the .java at compile time?
For example:
#Entity
... class ... {
#Id
long id
}
I would like to comment out all the Annotations and Create a ORM-Mapping.xml / Persistence according to the entitys
The annotations are mostly based on the configuration files which enable/disable their recognition.
Use the Spring profiles to distinguish the configuration classes. If the special profile will appear, no configuration classes will be recognized. The solution requires to make all the configurations configurable according to the Spring profiles.
#Configuration
#Profile("noAnnotations")
public class SomeConfigurationClass
It's possible. Project lombok modifies compiled code however there's no exposed API to do that. (See How does lombok work?) Which is what you want if you have to strip annotations. Disabling all annotations at runtime is probably not reasonable. If you just want to generate something from annotations found in compiled classes that is much simpler
What you describe sounds like you're looking for something like a C/C++ preprocessor/templating - feature?
Maybe Annotation Processing can help you https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/Processor.html
Apart from that - inferring a persistence.xml from your entities annotations is something the Spring Framework does.
I am using Spring Declarative Annotation based caching in my project .
applicationContext.xml
<cache:annotation-driven />
Currently, everything works perfectly using spring annotation based caching.
We use ehCache and ConcurrentHashMap based underline caching mechanism in development and local environment.
Now there is a requirement in project where I need to update the behavior of Spring cache framework with some specific business requirements.
I wonder if any one help me to figure it out how can I replace
<cache:annotation-driven />
this annotation with any spring class definition where I can customize the behavior?
Check out org.springframework.cache.annotation.EnableCaching.
Look at the comments in the source code.
It does the equivalent of the < cache:annotation-driven /> but in spring java config.
You will prolly need to override this class: org.springframework.cache.aspectj.AnnotationCacheAspect
Its responsible for wiring the advise in.
This answer lead me in the right direction. The thing that I found about the inner workings of the caching support from spring is that its not Dependency injected outside of the cacheManager and KeyGenerator implementations. I wanted to subclass/extend the CacheAspectSupport and found that this class is first extended by CacheInterceptor but then that class is created using new statements in a class ProxyCachingConfiguration. To be able to replace the one class/method would take replacing a whole list of classes which doesn't sound very spring friendly (admittedly i could be missing something).
What i was expecting from the replacement of the line was a fully listed out set of spring beans that composed all of the AOP pointcuts, advice/aspects, etc. that make up the caching support, but it seems like this is alål just statically created classes with tight coupling between each other.
As I started working with Hibernate a few days ago, I was just wondering : suppose you're starting a project from scratch. Would you use annotation-based mapping or Hibernate mapping files, to generate the database schema.
It is my understanding that Hibernate mapping files offer some features that you won't find (at least, not the exact equivalent) with annotations. But still, I have the feeling that nowadays, projects using Hibernate would rather go for annotation-based than Hibernate mapping files.
Has anybody ever chosen mapping files over annotations, and if so, for what reasons?
What advantages I see in using #Annotations:
compiler-safe
based on #Entity you can easily distinguish entity from no-entity
with packagesToScan Spring's feature entites are easily scannable
moving entites from packages to packages or class renaming is easy
What advantages I see in using XML:
it does not litters java classes with unnecessary vendor-specific
annotations (imagine java model class with JPA, JAXB, SOLRJ
annotations)
configuration in one place
easier to maintain as a whole
We use annotations, but keep XML as an option.
Go ahead with annotations any day. The XML configurations where really over used and saving the metadata inside the class is a good viable option.
Annotations will help you map the relationships better and it will align you to the JPA standard as hibernate uses mostly JPA annotations. There are no real problems using annotations and there is not much trade-off either. It has superior advantages over the XML based configurations. There might be few hacks missing when you use annotations but they will come along.
It is even possible to use annotations for new classes in a legacy project that has XML based mapping as told here.
The mapping in xml are not as illustrious as with annotation bases. So using annotations is more elegant at least for mapping.
Just trying to understand how Java annotations work under the covers.
Seeing as spring relies on annotations and scanning the object graph for DI and AOP (reflection), curious how things actually work.
With spring, are all lookup mappings etc. done at startup, so at runtime spring looks at its own inner mappings for DI/AOP/etc. instead of scanning the entire object graph?
Performance wise, if what I am guessing above is correct, it is basically performing a hash lookup?
Spring scans classes in the specified package when <context:component-scan> is present in the config.
Otherwise, Spring only looks at the annotations of classes explicitly declared in the config.
It is not true that Spring "relies" on annotations. Configuring your classes via annotations is just one option, using XML or other configuration files is another.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In a few large projects i have been working on lately it seems to become increasingly important to choose one or the other (XML or Annotation). As projects grow, consistency is very important for maintainability.
My questions are: what are the advantages of XML-based configuration over Annotation-based configuration and what are the advantages of Annotation-based configuration over XML-based configuration?
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. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.
I haven't used JPA annotations, so I don't know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn't care where its information came from, it should just care what it can do with its information. But if you like JPA (I don't have any expirience with it), by all means, go for it.
In general:
If an annotation provides functionality and acts as a comment in and of itself, and doesn't tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won't change the main functionality of the code, and hence doesn't belong in the source files.
There is a wider issue here, that of externalised vs inlined meta-data. 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. As a result, new hair-on-fire frameworks like JPA tend to put more emphasis on them. More mature APIs like native Hibernate offer both, because it's known that neither one is enough.
I always think about annotations as some kind of indicator of what a class is capable of, or how it interacts with others.
Spring XML configuration on the other hand to me is just that, configuration
For instance, information about the ip and port of a proxy, is definetly going into an XML file, it is the runtime configuration.
Using #Autowire,#Element to indicate the framework what to do with the class is good use of annotations.
Putting the URL into the #Webservice annotation is bad style.
But this is just my opinion.
The line between interaction and configuration is not always clear.
I've been using Spring for a few years now and the amount of XML that was required was definitely getting tedious. Between the new XML schemas and annotation support in Spring 2.5 I usually do these things:
Using "component-scan" to autoload classes which use #Repository, #Service or #Component. I usually give every bean a name and then wire them together using #Resource. I find that this plumbing doesn't change very often so annotations make sense.
Using the "aop" namespace for all AOP. This really works great. I still use it for transactions too because putting #Transactional all over the place is kind of a drag. You can create named pointcuts for methods on any service or repository and very quickly apply the advice.
I use LocalContainerEntityManagerFactoryBean along with HibernateJpaVendorAdapter to configure Hibernate. This lets Hibernate easily auto-discover #Entity classes on the classpath. Then I create a named SessionFactory bean using "factory-bean" and "factory-method" referring to the LCEMFB.
An important part in using an annotation-only approach is that the concept of a "bean name" more or less goes away (becomes insignificant).
The "bean names" in Spring form an additional level of abstraction over the implementing classes. With XML beans are defined and referenced relative to their bean name. With annotations they are referenced by their class/interface. (Although the bean name exists, you do not need to know it)
I strongly believe that getting rid of superfluous abstractions simplifies systems and improves productivity. For large projects I think the gains by getting rid of XML can be substantial.
It depends on what everything you want to configure, because there are some options that cannot be configured with anotations. If we see it from the side of annotations:
plus: annotations are less talky
minus: annotations are less visible
It's up to you what is more important...
In general I would recommend to choose one way and use it all over some closed part of product...
(with some exceptions: eg if you choose XML based configurations, it's ok to use #Autowire annotation. It's mixing, but this one helps both readability and maintainability)
I think that visibility is a big win with an XML based approach. I find that the XML isn't really that bad, given the various tools out there for navigating XML documents (i.e. Visual Studio + ReSharper's File Structure window).
You can certainly take a mixed approach, but that seems dangerous to me if only because, potentially, it would make it difficult for new developers on a project to figure out where different objects are configured or mapped.
I don't know; in the end XML Hell doesn't seem all that bad to me.
There are other aspect to compare like refactoring and other code changes. when using XML it takes serous effort to make refactoring because you have to take care of all the XML content. But it is easy when using Annotations.
My preferred way is the Java based configuration without (or minimal) annotations. http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-java
I might be wrong, but I thought Annotations (as in Java's #Tag and C#'s [Attribute]) were a compile-time option, and XML was a run-time option. That to me says the are not equivalent and have different pros and cons.
I also think a mix is the best thing, but it also depends on the type of configuration parameters.
I'm working on a Seam project which also uses Spring and I usually deploy it to different development and test servers. So I have split:
Server specific configuration (Like absolute paths to resources on server): Spring XML file
Injecting beans as members of other beans (or reusing a Spring XML defined value in many beans): Annotations
The key difference is that you don't have to recompile the code for all changing server-specific configurations, just edit the xml file.
There's also the advantage that some configuration changes can be done by team members who don't understand all the code involved.
In the scope of DI container, I consider annotation based DI is abusing the use of Java annotation. By saying that, I don't recommend to use it widely in your project. If your project does really needs the power of DI container, I would recommend to use Spring IoC with Xml based configuration option.
If it is just for a sake of Unit-test, developers should apply Dependency Inject pattern in their coding and take advantages from mocking tools such as EasyMock or JMock to circumvent dependencies.
You should try to avoid using DI container in its wrong context.
Configuration information that is always going to be linked to a specific Java component (class, method, or field) is a good candidate to be represented by annotations. Annotations work especially well in this case when the configuration is core to the purpose of the code. Because of the limitations on annotations, it's also best when each component can only ever have one configuration. If you need to deal with multiple configurations, especially ones that are conditional on anything outside the Java class containing an annotation, annotations may create more problems than they solve. Finally, annotations cannot be modified without recompiling the Java source code, so anything that needs to be reconfigurable at run time can't use annotations.
Please refer following links. They might be useful too.
Annotations vs XML, advantages and disadvantages
http://www.ibm.com/developerworks/library/j-cwt08025/
This is the classic 'Configuration versus Convention' question. Personal taste dictates the answer in most cases. However, personally I prefer Configuration (i.e. XML based) over Convention. IMO IDE's are sufficiently robust enough to overcome some of the XML hell people often associate w/ the building and maintaining an XML based approach. In the end, I find the benefits of Configuration (such as building utilities to build, maintain and deploy the XML config file) outweighs Convention in the long run.
I use both. Mostly XML, but when I have a bunch of beans that inherit from a common class and have common properties, I use annotations for those, in the superclass, so I don't have to set the same properties for each bean. Because I'm a bit of a control freak, I use #Resource(name="referredBean") instead of just autowiring stuff (and save myself a lot of trouble if I ever need another bean of the same class as the original referredBean).
There are some pros and cons of annotation configuration from my experience:
When it comes to JPA configuration since it is done once and usually are not changed quite often I prefer to stick to annotation configuration. There maybe a concern regarding possibility to see a bigger picture of configuration - in this case I use MSQLWorkbench diagrams.
Xml configuration is very good to get a bigger picture of application but it maybe cumbersome to find some errors until runtime. In this case Spring #Configuration annotation sounds as a better choice since it let you see a bigger picture as well and also allows to validate configuration on compile time.
As for Spring configuration I prefer to combine both approaches: use #Configuration annotation with Services and Query interfaces and xml configuration for dataSource and spring configuration stuff like context:component-scan base-package="..."
But xml configuration bits java annotations when it comes to flow configuration(Spring Web Flow or Lexaden Web Flow) since it is extremely important to see a bigger picture of the whole business process. And it sounds cumbersome to have it implemented with annotations approach.
I prefer combining both approaches - java annotations and essential xml minimum that minimize configuration hell.
For Spring Framework I like the idea of being able to use the #Component annotation and setting the "component-scan" option so that Spring can find my java beans so that I do not have to define all of my beans in XML, nor in JavaConfig. For example, for stateless singleton java beans that simply need to be wired up to other classes (via an interface ideally) this approach works very well. In general, for Spring beans I have for the most part moved away from Spring XML DSL for defining beans, and now favor the use of JavaConfig and Spring Annotations because you get some compile time checking of your configuration and some refactoring support that you don't get with Spring XML configuration. I do mix the two in certain rare cases where I've found that JavaConfig/Annotations can't do what is available using XML configuration.
For Hibernate ORM (haven't used JPA yet) I still prefer the XML mapping files because annotations in domain model classes to some degree violates The Clean Architecture which is a layering architectural style I have adopted over the past few years. The violation occurs because it requires the Core Layer to depend on persistence related things such as Hibernate or JPA libraries and it makes the domain model POJOs a bit less persistence ignorant. In fact the Core Layer is not supposed to depend on any other infrastructure at all.
However, if The Clean Architecture is not your "cup of tea" then I can see there are definitely advantages (such as convenience and maintainability) of using Hibernate/JPA annotations in domain model classes over separate XML mapping files.