Implementing DI with Spring Annotations
You can use Beans without a Bean configuration file by adding annotations to classes. This is the basic approach for using Beans and components.
Controlling Beans with Annotations
Configuration styles have shifted from XML files to annotations. An annotation is text beginning with @ on a class, method, or field declaration, such as @Override.
Spring supports both configuration-file and annotation-based approaches. This page explains annotation-based configuration.
Creating a Bean Configuration Class
Annotation-based configuration uses a Java class instead of a Bean configuration file.
package com.devkuma.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SampleBeanConfig {
@Bean
public SampleBeanInterface sampleBean() {
return new SampleBean("Instance created by the configuration class.");
}
}
@Configurationindicates that a class configures Beans.@Beanmarks a method that creates a Bean instance. The method must return the Bean.
Updating the App Class
ApplicationContext app =
new AnnotationConfigApplicationContext(SampleBeanConfig.class);
SampleBeanInterface bean1 =
app.getBean(SampleBeanInterface.class);
System.out.println(bean1);
AnnotationConfigApplicationContext creates an ApplicationContext from a configuration class. Use getBean() with the desired class to retrieve the Bean.
Creating and Using a Component
Creating a Component
Spring can define classes with richer behavior as components and use them like Beans.
package com.devkuma.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanHolder {
@Autowired
private SampleBeanInterface bean;
public void showMessage() {
System.out.println("*print by BeanHolder*");
System.out.println(bean);
System.out.println("*end*");
}
}
@Componentmarks the class as a component.@Autowiredfinds a compatible Bean and assigns it automatically.
Add @ComponentScan to SampleBeanConfig so that Spring discovers components, creates instances, and registers them in the ApplicationContext.
Using a Component
ApplicationContext app =
new AnnotationConfigApplicationContext(SampleBeanConfig.class);
BeanHolder holder = app.getBean(BeanHolder.class);
holder.showMessage();
Although BeanHolder is not declared directly in the configuration class, @ComponentScan discovers its @Component annotation. @Autowired injects SampleBean into its field.
Annotations let Spring create and connect required Beans and components automatically. DI and Bean management are foundational Spring Framework concepts.