Quiz: Beans and Spring Context
Test your knowledge on beans and the application context.
30 questions - Click on each question to reveal the answer.
Questions 1-15: Beans
Question 1: What is a Spring bean?
Answer: A bean is an object managed by the Spring IoC container:
- Created and configured by Spring
- Automatic dependency injection
- Managed lifecycle
- Singleton by default
Question 2: How to declare a bean with an annotation?
Answer:
// With stereotype (automatic scan)
@Component
public class MyService { }
@Service
public class UserService { }
@Repository
public class UserRepository { }
@Controller
public class UserController { }
Question 3: How to declare a bean with @Bean?
Answer:
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.registerModule(new JavaTimeModule());
}
}
Question 4: What is the difference between @Component and @Bean?
Answer:
| @Component | @Bean |
|---|---|
| On a class | On a method |
| Auto-detected by scan | Explicitly declared |
| Classes you control | Third-party classes |
| Limited configuration | Full control |
Question 5: What is the default name of a bean?
Answer: The class name in camelCase:
@Component
public class UserService { }
// Name: userService
@Bean
public RestTemplate myRestTemplate() { }
// Name: myRestTemplate
Customize:
@Component("customName")
@Bean("customName")
Question 6: How to retrieve a bean by its name?
Answer:
@Autowired
private ApplicationContext context;
public void example() {
UserService service = context.getBean("userService", UserService.class);
// Or by type
UserService service = context.getBean(UserService.class);
}
Question 7: What is the lifecycle of a bean?
Answer:
- Instantiation: object creation
- Injection: dependency injection
- Initialization: @PostConstruct methods
- Usage: bean ready
- Destruction: @PreDestroy methods
Question 8: How to execute code after initialization?
Answer:
@Component
public class DataLoader {
@PostConstruct
public void init() {
log.info("Bean initialized");
loadData();
}
}
// Or with @Bean
@Bean(initMethod = "init")
public MyService myService() { }
Question 9: How to execute code before destruction?
Answer:
@Component
public class ResourceManager {
@PreDestroy
public void cleanup() {
log.info("Cleaning up resources");
closeConnections();
}
}
// Or with @Bean
@Bean(destroyMethod = "close")
public DataSource dataSource() { }
Question 10: What are InitializingBean and DisposableBean?
Answer: Alternative interfaces for the lifecycle:
@Component
public class MyBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() {
// After injection
}
@Override
public void destroy() {
// Before destruction
}
}
Prefer @PostConstruct/@PreDestroy for less coupling.
Question 11: How to implement ApplicationRunner?
Answer:
@Component
public class StartupRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
log.info("Application started");
// Arguments: args.getOptionValues("config")
}
}
Executed after the full context startup.
Question 12: How to implement CommandLineRunner?
Answer:
@Component
public class DataInitializer implements CommandLineRunner {
private final UserRepository repository;
@Override
public void run(String... args) {
repository.save(new User("Admin"));
log.info("Data initialized");
}
}
Question 13: How to order the execution of runners?
Answer:
@Component
@Order(1)
public class FirstRunner implements CommandLineRunner { }
@Component
@Order(2)
public class SecondRunner implements CommandLineRunner { }
Question 14: How to create a conditional bean?
Answer:
@Bean
@ConditionalOnProperty(name = "cache.enabled", havingValue = "true")
public CacheManager cacheManager() { }
@Bean
@ConditionalOnMissingBean(DataSource.class)
public DataSource defaultDataSource() { }
@Bean
@Profile("dev")
public DevService devService() { }
Question 15: What is @Lazy?
Answer: Delays the creation of the bean until first access:
@Component
@Lazy
public class HeavyService {
public HeavyService() {
// Called only on first access
}
}
// Or at injection
public MyController(@Lazy HeavyService service) { }
Questions 16-30: Context and Scopes
Question 16: What is the ApplicationContext?
Answer: The central Spring container that:
- Manages all beans
- Provides dependency injection
- Publishes events
- Loads resources
- Manages internationalization
Question 17: What are the available bean scopes?
Answer:
| Scope | Description |
|---|---|
singleton | One instance per context (default) |
prototype | New instance for each request |
request | One instance per HTTP request |
session | One instance per HTTP session |
application | One instance per ServletContext |
Question 18: How to define the scope of a bean?
Answer:
@Component
@Scope("prototype")
public class PrototypeBean { }
@Bean
@Scope("request")
public RequestContext requestContext() { }
// Or with constants
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Question 19: What problem arises when injecting a prototype into a singleton?
Answer: The singleton always keeps the same instance of the prototype:
@Component // Singleton
public class SingletonService {
private final PrototypeBean proto; // Always the same instance!
public SingletonService(PrototypeBean proto) {
this.proto = proto;
}
}
Solution: use ObjectProvider or @Lookup.
Question 20: How to use ObjectProvider?
Answer:
@Component
public class SingletonService {
private final ObjectProvider<PrototypeBean> protoProvider;
public void doWork() {
PrototypeBean proto = protoProvider.getObject(); // New instance
}
}
Question 21: How to use @Lookup?
Answer:
@Component
public abstract class SingletonService {
@Lookup
protected abstract PrototypeBean getPrototype();
public void doWork() {
PrototypeBean proto = getPrototype(); // New instance
}
}
Question 22: How to listen to context events?
Answer:
@Component
public class ContextListener {
@EventListener
public void onContextRefreshed(ContextRefreshedEvent event) {
log.info("Context refreshed");
}
@EventListener
public void onContextClosed(ContextClosedEvent event) {
log.info("Context closed");
}
}
Question 23: How to publish a custom event?
Answer:
// Event
public class UserCreatedEvent extends ApplicationEvent {
private final User user;
public UserCreatedEvent(Object source, User user) {
super(source);
this.user = user;
}
}
// Publishing
@Service
public class UserService {
private final ApplicationEventPublisher publisher;
public void createUser(User user) {
userRepository.save(user);
publisher.publishEvent(new UserCreatedEvent(this, user));
}
}
// Listening
@Component
public class UserEventListener {
@EventListener
public void onUserCreated(UserCreatedEvent event) {
log.info("User created: {}", event.getUser().getName());
}
}
Question 24: How to listen to an event asynchronously?
Answer:
@EnableAsync
@Configuration
public class AsyncConfig { }
@Component
public class AsyncListener {
@Async
@EventListener
public void onEvent(MyEvent event) {
// Executed in another thread
}
}
Question 25: How to access the Spring environment?
Answer:
@Component
public class ConfigService {
private final Environment env;
public ConfigService(Environment env) {
this.env = env;
}
public void showConfig() {
String property = env.getProperty("app.name");
String[] profiles = env.getActiveProfiles();
boolean isDev = env.acceptsProfiles(Profiles.of("dev"));
}
}
Question 26: How to load external resources?
Answer:
@Component
public class ResourceLoader {
@Value("classpath:data/config.json")
private Resource configResource;
public void load() throws IOException {
String content = new String(configResource.getInputStream().readAllBytes());
}
}
Question 27: How to implement EnvironmentPostProcessor?
Answer:
public class CustomEnvProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication app) {
// Modify the environment before startup
Map<String, Object> props = new HashMap<>();
props.put("custom.property", "value");
env.getPropertySources().addFirst(new MapPropertySource("custom", props));
}
}
Register in META-INF/spring.factories.
Question 28: How to use Spring profiles?
Answer:
// Bean active only in dev
@Component
@Profile("dev")
public class DevOnlyService { }
// Bean active except in prod
@Component
@Profile("!prod")
public class NonProdService { }
// Multiple profiles
@Component
@Profile({"dev", "test"})
public class DevTestService { }
Question 29: How to define beans in separate configurations?
Answer:
@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() { }
}
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain() { }
}
@Configuration
@Import({DatabaseConfig.class, SecurityConfig.class})
public class AppConfig { }
Question 30: How to test a Spring context?
Answer:
@SpringBootTest
class ContextTest {
@Autowired
private ApplicationContext context;
@Test
void contextLoads() {
assertThat(context).isNotNull();
assertThat(context.getBean(UserService.class)).isNotNull();
}
@Test
void beanExists() {
assertThat(context.containsBean("userService")).isTrue();
}
}
Score
| Score | Level |
|---|---|
| 27-30 | Excellent - Mastered beans and context |
| 21-26 | Good - Some revisions needed |
| 15-20 | Average - Review the chapter |
| Less than 15 | Needs review |