Java Notes
Complete guide to Spring Beans - bean definition, stereotype annotations, bean naming, lazy initialization, conditional beans, and bean ordering.
What is a Spring Bean?
A Spring Bean is any object that is managed by the Spring IoC container. The container is responsible for creating, configuring, wiring dependencies, and managing the lifecycle of beans.
Bean Naming
// Default name = class name with lowercase first letter
@Service
public class UserService { } // Bean name: "userService"
// Custom name
@Service("customUserService")
public class UserService { } // Bean name: "customUserService"
// @Bean name
@Bean("emailSender")
public EmailService emailService() { return new SmtpEmailService(); }
// Multiple names (aliases)
@Bean(name = {"emailSender", "mailer", "notifier"})
public EmailService emailService() { return new SmtpEmailService(); }Lazy Initialization
By default, singleton beans are created at container startup (eager). Use @Lazy to defer:
@Service
@Lazy // Created only when first requested
public class ReportGenerator {
public ReportGenerator() {
System.out.println("ReportGenerator created — expensive initialization");
// Load templates, connect to external services, etc.
}
}
// Lazy at injection point
@Service
public class DashboardService {
@Autowired
@Lazy // Proxy injected; real bean created on first method call
private ReportGenerator reportGenerator;
}
// Global lazy initialization
@Configuration
@ComponentScan("com.example")
@Lazy // ALL beans in this config are lazy
public class AppConfig { }ReportGenerator created — expensive initialization
Conditional Beans
// Bean created only if condition is met
@Bean
@Conditional(DatabaseAvailableCondition.class)
public DataSource dataSource() { }
// Spring Boot shortcuts
@Bean
@ConditionalOnProperty(name = "feature.email.enabled", havingValue = "true")
public EmailService emailService() { }
@Bean
@ConditionalOnClass(name = "com.redis.RedisClient")
public CacheManager redisCacheManager() { }
@Bean
@ConditionalOnMissingBean(CacheManager.class)
public CacheManager defaultCacheManager() { }Bean Ordering
@Component
@Order(1) // Lower number = higher priority
public class SecurityFilter implements Filter { }
@Component
@Order(2)
public class LoggingFilter implements Filter { }
@Component
@Order(3)
public class CorsFilter implements Filter { }Depends-On
// Ensure DataSource is created before UserRepository
@Service
@DependsOn("dataSource")
public class UserRepository { }
@Bean
@DependsOn({"cacheManager", "dataSource"})
public UserService userService() { }Primary and Qualifier
When multiple beans of the same type exist:
// Multiple implementations
@Service
@Primary // Default choice when no qualifier specified
public class SmtpEmailService implements EmailService { }
@Service("smsNotifier")
public class SmsNotificationService implements EmailService { }
// Using @Qualifier to choose specific implementation
@Service
public class OrderService {
@Autowired
@Qualifier("smsNotifier")
private EmailService notificationService;
}FactoryBean
For complex bean creation logic:
@Component
public class ConnectionFactoryBean implements FactoryBean<Connection> {
@Value("${db.url}")
private String url;
@Override
public Connection getObject() throws Exception {
return DriverManager.getConnection(url, "root", "password");
}
@Override
public Class<?> getObjectType() {
return Connection.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
// Usage — Spring returns Connection, not the FactoryBean
@Autowired
private Connection connection; // Gets the Connection objectBean Aware Interfaces
@Service
public class AwareService implements BeanNameAware, ApplicationContextAware, EnvironmentAware {
private String beanName;
private ApplicationContext context;
private Environment environment;
@Override
public void setBeanName(String name) {
this.beanName = name; // "awareService"
}
@Override
public void setApplicationContext(ApplicationContext ctx) {
this.context = ctx;
}
@Override
public void setEnvironment(Environment env) {
this.environment = env;
}
public void printInfo() {
System.out.println("Bean name: " + beanName);
System.out.println("Active profiles: " +
Arrays.toString(environment.getActiveProfiles()));
System.out.println("Total beans: " +
context.getBeanDefinitionCount());
}
}Best Practices
| Practice | Reason |
|---|---|
| Use constructor injection | Immutability, required deps, testability |
Prefer @Service/@Repository over @Component | Clearer intent, extra features |
Use @Primary for default implementations | Avoids qualifier everywhere |
| Make beans stateless (singleton-safe) | Thread safety |
Use @Lazy for expensive beans | Faster startup |
Put @Bean methods in @Configuration | Full proxy mode, method interception |
Interview Key Points
- A bean is any object managed by Spring IoC container
@Componentis generic;@Service,@Repository,@Controlleradd semantics@Repositoryadds automatic exception translation (SQL → Spring exceptions)- Default scope is singleton; default initialization is eager
@Primarymarks the default bean;@Qualifierselects specific bean@Lazydefers creation until first use (proxy injected)@Beanin@Configurationclass creates beans programmatically- Bean names default to class name with lowercase first letter
Summary
In this chapter, we learned about Spring Beans in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Spring Beans.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, spring, framework, beans
Related Java Master Course Topics