Spring / Spring7 basics Interview questions
What is the purpose of the @Bean annotation?
@Bean is applied to a method inside a @Configuration (or @Component) class to tell Spring that the method's return value should be registered and managed as a bean. It's typically used when you need to wire a third-party class you don't own, or when bean creation needs custom logic that a simple @Component can't express.
@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); return mapper; }
By default, the bean's name matches the method name (objectMapper here), though it can be overridden with @Bean(name = "..."). Unlike @Component, @Bean doesn't rely on classpath scanning - it's an explicit, imperative registration.
More Related questions...