Wednesday, December 30, 2015

What is @Configuration in Spring - Spring 3 JavaConfig example

Ref:- http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch03.html

Since Spring 3, JavaConfig features are included in core Spring module, it allow developer to move bean definition and Spring configuration out of XML file into Java class.
But, you are still allow to use the classic XML way to define beans and configuration, the JavaConfig is just another alternative solution.
See the different between classic XML definition and JavaConfig to define a bean in Spring container.
Spring XML file :
<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-3.0.xsd">
 
 <bean id="helloBean" class="com.mkyong.hello.impl.HelloWorldImpl">
  
</beans>
Equivalent configuration in JavaConfig :
package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;

@Configuration
public class AppConfig {
 
    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
 
}

No comments:

Post a Comment