- @Configuration itself is a Component
- Hence @ComponentScan is required for @Configuration as well
- @Configuration annotation indicates that a class declares one or more
@Bean
methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime. @Configuration
is the heart of the Java-based configuration mechanism that was introduced in Spring 3. It provides an alternative to XML-based configuration.- Where as
@Configuration
is used to create component which is used by spring framework to create the application context
It is a way in which you can load a normal Java Object into a Spring Container
public interface DemoManager { public String getServiceName(); } public class DemoManagerImpl implements DemoManager { @Override public String getServiceName() { return "My first service with Spring 3"; } }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.howtodoinjava.core.beans.DemoManager; import com.howtodoinjava.core.beans.DemoManagerImpl; @Configuration public class ApplicationConfiguration { @Bean(name="demoService") public DemoManager helloWorld() { return new DemoManagerImpl(); } }
package com.howtodoinjava.core.verify; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.howtodoinjava.core.beans.DemoManager; import com.howtodoinjava.core.config.ApplicationConfiguration; public class VerifySpringCoreFeature { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class); DemoManager obj = (DemoManager) context.getBean("demoService"); System.out.println( obj.getServiceName() ); } }
Difference between @Configuration and @Component
Reference :