Benefits of JavaConfig over XML configurations in Spring?

筅森魡賤 提交于 2019-11-28 07:11:49

There are some advantages

  1. Java is type safe. Compiler will report issues if you are configuring right bean class qualifiers.
  2. XML based on configuration can quickly grow big. [Yes we can split and import but still]
  3. 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.

References: Java configuration advantages Some more reasons

According to the Spring 5 reference

XML-based metadata is not the only allowed form of configuration metadata. The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written. These days many developers choose Java-based configuration for their Spring applications.

it means nowadays, people are moving towards java based config

for example: Spring web-mvc config in xml

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.0.xsd     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:component-scan base-package="hms.controller" />
    <context:component-scan base-package="dao" />
    <context:component-scan base-package="hms.service" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>  

and same config in java based style

@Configuration
@EnableWebMvc

@ComponentScans({
        @ComponentScan("hms.controller"),
        @ComponentScan("dao"),
        @ComponentScan("hms.service")      
})
public class WebMVCConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

what is easy to understand? Obviously, the Java-based config is easy to understand.

people who write codes and others can easily understand java code than XML. and you do not need to know about XML if you only know Java.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!