What are annotations
Annotations is a feature introduced in JDK 1.5. Can be seen as an extended template for a class/method, each class/method according to the rules in the annotation class, to annotate the class/method different parameters, in the use of the different classes/methods can be used to annotate the various parameters and values.
Why do you use annotations
Before JDK 1.5, Java had not introduced annotations, this time if we were to declare a Bean in Spring, we could only configure it through XML.
public class demoservice{}
<bean id= "Demoservice" class= "Com.chenshuyi.DemoService"/>
But with annotations, we don't have to write an XML configuration file, and we can do the Bean declaration directly on the Demoservice class.
public class demoservice{}
On the surface, we reduce the amount of development code by reducing an XML configuration file by annotating it. But is this really why we use annotations instead of XML config files?
Before answering this question, let's review the features of the above two configuration methods:
-
for the way annotations are. We will find that it is very tightly bound to the code, so annotations are better suited to doing something that is highly relevant to the code, such as exposing the service to the bean.
-
for how XML is configured. We'll find that it isolates the configuration from the code, so the XML configuration is better suited to doing some global, code-independent operations, such as global configuration.
I believe that many people have previously understood the annotation is to facilitate development. But the fact that the use of annotations or XML should be judged by the relevance of the configuration to the code. If the code is highly correlated with configuration, use annotations to configure it, otherwise use the XML configuration.
Comparison of annotations and configuration files
Advantages:
-
Configuration file
-
Follow the OCP development principles and modify the configuration file to expand functionality (OCP Open Closed Principle)
-
Centrally manage the composition of objects and objects, easy to read
-
Annotations
-
Fast development speed
-
Easy to find the source of errors during compilation
Disadvantages:
-
Configuration file
-
Relatively slow development speed
-
Compilation is difficult to check out errors, running errors difficult to locate, difficult to debug
-
Annotations
-
Decentralized management, basic on every class
-
The OCP development principle is not followed when extending functionality
Original Address
What about the annotations (a) | Why use annotations?
Java annotations-Why use annotations