Sobes.tech
Middle

Where is the @Bean annotation used?

sobes.tech AI

Answer from AI

The @Bean annotation is used on methods within classes annotated with @Configuration. It indicates that the method returns an object that the Spring IoC container should register as a Bean.

Main application areas:

  • Creating and configuring objects that are difficult or impossible to create using @Component scanning (e.g., third-party libraries).
  • Providing Spring access to instances of classes from other frameworks or modules.
  • Defining beans with special dependencies or lifecycle.

Example:

package com.example.demo.config;

import com.example.demo.service.MyService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // Indicates that this class contains @Bean methods
public class AppConfig {

    @Bean // Annotation on method returning a bean
    public MyService myService() {
        return new MyService(); // Creating an instance of MyService
    }

    @Bean // Another bean that may depend on the previous one
    public AnotherBean anotherBean(MyService myService) {
        return new AnotherBean(myService);
    }
}
Where is the @Bean annotation used? — Java - sobes.tech