Super detailed SpringXML and annotation form configuration comparison

  • j3_liuliang
  • The two configuration methods used when learning Spring configuration, so record the following, if you are interested, you can take a look!

1. XML configuration form VS annotation configuration form

XML:

  1. Write SpringConfig.xml file

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       // 定义Bean信息
       <bean id="user" class="cn.liuliang.studysoundcodespring.entity.User">
           <property name="name" value="j3-liuliang"/>
           <property name="age" value="18"/>
       </bean>
    </beans>
    
  2. Write test class

    @Test
    public void test02(){
           
           
        // 根据xml配置文件获取应用上下文
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringConfig.xml");
        // 根据class获取相关bean
        User bean = applicationContext.getBean(User.class);
        System.out.println(bean);
    }
    
  3. result:

    Insert picture description here

注解

  1. Define annotation configuration class

    @Configuration //声明该类是配置类
    @ComponentScan("cn.liuliang.studysoundcodespring") //包扫描
    public class SpringConfig {
           
           
    /**
      * 向容器中主入一个bean组件
      * @return
      */
     @Bean
     public User user(){
           
           
         // 通过new创建对象,放入容器中
         return new User("j3-liuliang",28);
     }
    }
    
  2. Write test

    @Test
    public void test01(){
           
           
    // 注解配置类应用上下文
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    User user = applicationContext.getBean(User.class);
    System.out.println(user);
    }
    
  3. result

    Insert picture description here

Note: If it is used in the form of @Bean, the default name of the bean is the method name. If @Bean(value="bean's name"), then the bean name is specified

1.1 Comparison of advantages and disadvantages

注解

advantage

  • Simplified configuration
  • Simple to use, improve development efficiency

Disadvantage

  • Unable to configure the classes in the third-party jar package

XML

advantage

  • Loose coupling between classes, easy to expand and replace
  • The relationship between objects is clear at a glance

Disadvantage

  • The configuration is tedious, and an additional configuration needs to be maintained
  • The type is not safe, compile cannot help with the verification, the error will be found during the runtime

The above comparison is relatively simple, I think it is not enough (in a responsible attitude towards technology), but my own technical ability is limited and I can't sum up a more comprehensive comparison result!

下面是我在CSDN上看到的一位博主对注解与XML配置的比较,对比很全面, The original link

Insert picture description here

The difference between annotation and XML configuration

Note: It is a kind 分散式of metadata, and source code 紧绑定.

xml: is a kind 集中式of metadata, and source code 无绑定.

Therefore, the choice of annotation and XML can be viewed from two perspectives: decentralized or centralized, source code binding/no binding .

Disadvantages of annotations:

1. For example, when using spring annotations, many friends will find that the annotations are scattered into many classes, which is not easy to manage and maintain; this actually requires the help of tools, I currently use IDEA , which performs very well in this aspect; of course now There is also Spring's STS , which is also good; so with the help of tools, this problem can be solved;

2. The source code must be modified to turn on/off the annotation, because the annotation is bound to the source code. If you want to modify it, you need to change the source code. This has this problem, so if this is the case, you still use the XML configuration method; such as data source ;

3. Another disadvantage of annotations is flexibility. For example, the previously translated Spring Framework 4.0 M1: WebSocket support ; in terms of implementing complex logic, no XML is more powerful; annotations are either used or not, such as the previous jpa bean Validation, either all or none; it is painful to encounter this situation;

4. The other is that the convention is greater than the configuration, but when dealing with some complicated situations, annotations are still needed (such as Spring's data validation/data binding annotations are very powerful);

5. XML is better for general configuration, such as transaction configuration, such as database connection pool, etc., that is, general configuration is centralized, rather than decentralized. For example, many people use @Transactional to configure transactions. In many cases, this is a kind of Too decentralized configuration;

6. The XML method is much better than annotations in terms of scalability and complexity maintenance, such as which components are needed and which are not needed; in this situation, the annotation scanning mechanism is relatively inferior, because the rules are difficult to write or not at all May be written

The benefits of annotations:

1. XML configuration is sometimes verbose. At this time, annotations may be a better choice, such as jpa entity mapping; annotations are sometimes much more convenient than XML when dealing with some constant metadata, such as springmvc data binding. If you use xml to write more code;

2. The biggest advantage of annotation is that it simplifies the XML configuration; in fact, most of the annotations are seldom changed after being determined, so the use of annotations in some small and medium-sized projects provides development efficiency, so there is no need to go to the black;

3. Another advantage of annotation over XML is that it is type-safe. XML can only find problems during runtime.

Whether it’s annotations or XML, we still need some switch/replacement mechanisms to control special needs to change the all-or-nothing scheme.

Another call is that the agreement is greater than the configuration. This solution may be optimal in some scenarios, but it may not solve the problem in some complex situations, so the annotation is also a good solution at this time. Especially when using springmvc, the benefits can be realized.

Regardless of whether you use annotations or XML, the things you do are still those things, but annotations and XML are not omnipotent, you can meet your needs and solve the problem in a simpler way.

Just like discussing technical issues, many people have strong personal preferences to judge the quality of a thing. This kind of discussion has no meaning. Our ultimate goal is to solve the problem, so we should explore whether the problem can be solved. , Can you solve the problem in a more understandable way? Can you solve the problem more simply.

No matter whether the agreement is greater than the configuration, the annotation or the XML configuration, no one is optimal. It is important to choose the right solution in the right scenario. Just like a design pattern: it is a proven solution to a specific problem that recurs in a specific environment.

Concluding remarks

  • As the bloggers are not very knowledgeable, there will inevitably be mistakes. If you find a mistake or prejudice, please leave a message to point it out, and I will correct it.
  • If you think the article is not bad, your forwarding, sharing, liking, and commenting are your greatest encouragement.
  • Thank you for reading, welcome and thank you for your attention.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40399646/article/details/108905977