Spring Framwork

  • Inversion of Control Container

  • Aspect-Oriented Programming

  • Data Access Framework

  • Spring MVC

Spring Bean

  • Managed by Spring Container:

    • Spring beans are created, wired together, and managed by the Spring IoC container.

    • The container is responsible for the lifecycle of the beans.

  • Defined in Configuration:

    • Beans are usually defined in a Spring configuration file (XML, annotations, or Java-based configuration using @Configuration).
  • Singleton by Default:

    • By default, a bean is a singleton in Spring. This means that there is only one instance of the bean per Spring IoC container. You can change the scope to prototype or other scopes if needed.
  • Dependency Injection:

    • Spring beans can have their dependencies injected via constructor, setter methods, or field injection (annotations like @Autowired).

Define a Bean

Annotation-Based

  • Annotate the class with @Component, @Service, @Repository, or @Controller

  • Use @Autowired to inject dependencies

@Component
public class MyBean {
    // Bean logic
}

Java Config-Based

  • Use @Configuration and @Bean annotations
@Configuration
public class AppConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

Bean Lifecycle

A Spring bean goes through several stages during its lifecycle:

  1. Instantiation: The container creates the bean instance.

  2. Populating Properties: Dependencies are injected.

  3. Post-Initialization:

    • Custom initialization using @PostConstruct or InitializingBean interface.
  4. Ready for Use: The bean is available for use in the application.

  5. Destruction: Beans are cleaned up when the container is shut down, using @PreDestroy or DisposableBean interface.

Example:

Bean Definition:

@Component
public class HelloWorld {
    public String sayHello() {
        return "Hello, Spring Bean!";
    }
}

Main Application:

@SpringBootApplication
public class SpringApp {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(SpringApp.class, args);
        HelloWorld helloWorld = context.getBean(HelloWorld.class);
        System.out.println(helloWorld.sayHello());
    }
}

In this example:

  • The HelloWorld class is a Spring Bean managed by the IoC container.

  • The @Component annotation tells Spring to manage this class as a bean.

Spring beans enable the development of loosely coupled, modular, and testable applications. They are a fundamental concept in the Spring framework for building scalable and maintainable software.

Credit: @freeCodeCamp, @Bouali Ali