- Annotation in Spring is used to automatically inject values at runtime.
- The
@Configuration
annotation in Spring is used to indicate that a class is a source of configuration for theSpring IoC (Inversion of Control)
container. - In simple words, we can say that it tells Spring that this class is intended to be used as a
configuration
class in place ofXML
. - Annotations are used for
java-based
configuration opposite toXML
configuration.
- Create a class with
@Component
annotation which will act asbean
. - Create a class with
@Configuration
annotation which will inform theSpring container
that this class can be used asConfiguration
class. - Along with
@Configuration
also use@ComponentScan
annotation with thebasePackages
attribute containing names ofone or more base packages
where Spring should look for theseannotated components
. - Start the Spring IoC container by instantiating AnnotationConfigApplicationContext passing it the name of Configuration class.
- Finally, retrieve the bean using the
getBean()
method.
`
@Configuration
@ComponentScan(basePackages = "com.autowire.demo.beans")
public class AppConfig {
public AppConfig() {
System.out.println("AppConfig cons called");
}
}
`
- Note, If our bean classes and Configuration class are in the same package, then we can avoid using the basePackages attribute in the
@ComponentScan
annotation. - If we want to inject a bean not in the current package, then use attribute
basePackages
orbasePackageClasses
. - The attribute
basePackages
will takeargument
as a string object separated bycomma
. - The attribute
basePackageClasses
will take theargument
asClasses
as an object separated bycomma
. - The name will be
null
since we are not using@Autowired
for constructor having name as argument.
- The jar
spring-aop
is required for annotation processing and let spring automatically scan the bean fromConfiguration
class.