Skip to main content

Bean Creation

In Spring terminology, the objects that form the backbone of your application and are managed securely by the Spring IoC Container are called Beans.

A bean is fundamentally just a normal Java object that has been instantiated, assembled, and managed entirely by Spring. There are three primary approaches to dictating how beans are created.

1. Traditional XML Configuration​

In legacy Spring applications (Spring 2 & 3), beans were explicitly manually mapped using massive XML context files.


<beans>
<bean id="userService" class="com.example.UserService">

<property name="userRepository" ref="userRepo" />
</bean>

<bean id="userRepo" class="com.example.UserRepositoryImpl" />
</beans>

2. Component Scanning Annotations​

Modern Spring entirely relies on automated scanning. You place stereotyped annotations above your class definitions, and Spring automatically detects them on application boot.

  • @Component: A generic stereotype for any Spring-managed component.
  • @Service: Used structurally for business logic classes.
  • @Repository: Used for Data Access Objects (DAO). Automatically translates SQL exceptions into generic Spring errors.
  • @Controller: Used to map HTTP endpoints in Spring MVC.
@Service
public class EmailService {
public void sendEmail() { ... }
}

3. Java Configuration (@Configuration)​

Sometimes, you cannot use @Component—specifically when you lack access to the source code (for example, attempting to register a 3rd-party AmazonS3Client class as a bean). In this case, you use explicit Java configurations.

@Configuration
public class AwsConfig {

// The @Bean annotation tells Spring to take the returned object
// and manually register it inside the IoC Container!
@Bean
public AmazonS3Client s3Client() {
return new AmazonS3Client(new Credentials("user", "pass"));
}
}