How do I create and manage beans in Spring?

In Spring, a bean is an object managed by the Spring container.

Spring is responsible for:

  • creating the object
  • injecting its dependencies
  • managing its lifecycle
  • applying configuration
  • destroying it when the application shuts down

The container that manages beans is usually the ApplicationContext.


1. What Is a Spring Bean?

A Spring bean is just a normal Java object whose lifecycle is controlled by Spring.

For example:

@Service
public class UserService {

    public String getMessage() {
        return "Hello from UserService";
    }
}

UserService is an ordinary Java class, but because it is annotated with @Service, Spring detects it and manages it as a bean.


2. Common Ways to Create Beans

There are two main ways to create beans in Spring:

  1. Component scanning
  2. Manual bean registration using @Bean

Option 1: Create Beans with Component Scanning

This is the most common approach.

Spring scans your project for classes annotated with stereotypes such as:

@Component
@Service
@Repository
@Controller
@RestController

Example:

@Service
public class EmailService {

    public void sendEmail(String to, String message) {
        System.out.println("Sending email to " + to + ": " + message);
    }
}

Spring automatically creates an EmailService bean.


Common Bean Annotations

@Component

Generic Spring-managed component.

@Component
public class FileStorage {
}

Use this when the class does not fit a more specific role.


@Service

Used for service/business logic classes.

@Service
public class PaymentService {
}

@Repository

Used for data access classes.

@Repository
public class UserRepository {
}

In Spring Data JPA, repositories are often interfaces:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

Spring Data JPA creates the implementation automatically.


@Controller

Used for Spring MVC controllers that return views.

@Controller
public class PageController {
}

@RestController

Used for REST APIs.

@RestController
@RequestMapping("/api/users")
public class UserController {
}

@RestController is effectively @Controller plus @ResponseBody.


Option 2: Create Beans Manually with @Bean

Use @Bean when you want to create an object yourself and give it to Spring.

This is common for:

  • third-party classes
  • library objects
  • objects requiring special construction logic
  • configuration-based objects

Example:

@Configuration
public class AppConfig {

    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }
}

Now Spring manages a Clock bean.

You can inject it elsewhere:

@Service
public class TimeService {

    private final Clock clock;

    public TimeService(Clock clock) {
        this.clock = clock;
    }

    public Instant now() {
        return Instant.now(clock);
    }
}

@Component vs @Bean

Use @Component, @Service, or @Repository when the class is yours and should always be managed by Spring.

Use @Bean when you need explicit construction logic.

Example:

@Configuration
public class HttpClientConfig {

    @Bean
    public HttpClient httpClient() {
        return HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
    }
}

Here, HttpClient comes from the JDK, so you cannot annotate it with @Component.


3. Injecting Beans

Once Spring manages a bean, you usually use it through dependency injection.

The recommended style is constructor injection.

@Service
public class OrderService {

    private final PaymentService paymentService;
    private final EmailService emailService;

    public OrderService(PaymentService paymentService, EmailService emailService) {
        this.paymentService = paymentService;
        this.emailService = emailService;
    }

    public void placeOrder() {
        paymentService.charge();
        emailService.sendConfirmation();
    }
}

Spring sees that OrderService needs PaymentService and EmailService, then injects them automatically.


Constructor Injection with Lombok

If your project uses Lombok, you can write:

@Service
@RequiredArgsConstructor
public class OrderService {

    private final PaymentService paymentService;
    private final EmailService emailService;

    public void placeOrder() {
        paymentService.charge();
        emailService.sendConfirmation();
    }
}

@RequiredArgsConstructor generates the constructor for all final fields.

This is common in modern Spring applications.


4. Avoid Field Injection

You may see this style:

@Service
public class OrderService {

    @Autowired
    private PaymentService paymentService;
}

This works, but it is usually discouraged because:

  • it makes testing harder
  • dependencies are hidden
  • fields cannot be final
  • objects can be created in an invalid state

Prefer constructor injection instead.


5. Bean Names

Every bean has a name.

By default, Spring uses the class name with a lowercase-first letter.

@Service
public class PaymentService {
}

Default bean name:

paymentService

You can also give a custom name:

@Service("stripePaymentService")
public class StripePaymentService {
}

Or with @Bean:

@Bean("utcClock")
public Clock clock() {
    return Clock.systemUTC();
}

6. Handling Multiple Beans of the Same Type

If Spring finds multiple beans of the same type, the injection becomes ambiguous.

Example:

public interface PaymentProcessor {
    void process();
}
@Service
public class StripePaymentProcessor implements PaymentProcessor {

    @Override
    public void process() {
        System.out.println("Processing with Stripe");
    }
}
@Service
public class PaypalPaymentProcessor implements PaymentProcessor {

    @Override
    public void process() {
        System.out.println("Processing with PayPal");
    }
}

This is ambiguous:

@Service
public class CheckoutService {

    public CheckoutService(PaymentProcessor paymentProcessor) {
    }
}

Spring does not know which PaymentProcessor to inject.


Use @Primary

Mark one implementation as the default:

@Service
@Primary
public class StripePaymentProcessor implements PaymentProcessor {

    @Override
    public void process() {
        System.out.println("Processing with Stripe");
    }
}

Now Spring injects StripePaymentProcessor unless told otherwise.


Use @Qualifier

Choose a specific bean:

@Service
public class CheckoutService {

    private final PaymentProcessor paymentProcessor;

    public CheckoutService(
            @Qualifier("paypalPaymentProcessor") PaymentProcessor paymentProcessor
    ) {
        this.paymentProcessor = paymentProcessor;
    }
}

The qualifier usually matches the bean name.


7. Bean Scopes

By default, Spring beans are singleton scoped.

That means Spring creates one shared instance per application context.

@Service
public class UserService {
}

This is equivalent to:

@Scope("singleton")
@Service
public class UserService {
}

Common Bean Scopes

singleton

One instance per Spring container.

@Component
@Scope("singleton")
public class AppCache {
}

This is the default.


prototype

A new instance each time the bean is requested.

@Component
@Scope("prototype")
public class ReportBuilder {
}

request

One instance per HTTP request.

@Component
@RequestScope
public class RequestContext {
}

Useful in Spring MVC applications.


session

One instance per HTTP session.

@Component
@SessionScope
public class ShoppingCart {
}

8. Bean Lifecycle

Spring beans go through a lifecycle:

1. Bean definition discovered
2. Object created
3. Dependencies injected
4. Initialization callbacks run
5. Bean is ready to use
6. Destruction callbacks run when context closes

Initialization with @PostConstruct

With Jakarta imports, use:

import jakarta.annotation.PostConstruct;

@Service
public class CacheService {

    @PostConstruct
    public void init() {
        System.out.println("CacheService initialized");
    }
}

Cleanup with @PreDestroy

import jakarta.annotation.PreDestroy;

@Service
public class CacheService {

    @PreDestroy
    public void shutdown() {
        System.out.println("CacheService shutting down");
    }
}

9. Conditional Beans

Sometimes you only want a bean to exist under certain conditions.

In Spring Boot, common annotations include:

@ConditionalOnProperty
@ConditionalOnMissingBean
@ConditionalOnClass
@Profile

Example with profiles:

@Service
@Profile("dev")
public class DevEmailService implements EmailService {
}
@Service
@Profile("prod")
public class SmtpEmailService implements EmailService {
}

Run with:

spring.profiles.active=prod

Then only the prod bean is active.


10. Configuration Properties as Beans

For application configuration, prefer configuration properties instead of manually reading values.

@ConfigurationProperties(prefix = "mail")
public class MailProperties {

    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

Enable it:

@Configuration
@EnableConfigurationProperties(MailProperties.class)
public class MailConfig {
}

Example config:

mail.host=smtp.example.com
mail.port=587

Then inject it:

@Service
public class MailService {

    private final MailProperties mailProperties;

    public MailService(MailProperties mailProperties) {
        this.mailProperties = mailProperties;
    }
}

11. Getting Beans Programmatically

Most of the time, you should not call ApplicationContext#getBean() manually.

Prefer this:

@Service
public class ReportService {

    private final CsvExporter csvExporter;

    public ReportService(CsvExporter csvExporter) {
        this.csvExporter = csvExporter;
    }
}

Instead of this:

@Service
public class ReportService {

    private final ApplicationContext applicationContext;

    public ReportService(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void export() {
        CsvExporter exporter = applicationContext.getBean(CsvExporter.class);
    }
}

Programmatic lookup is sometimes useful for dynamic behavior, but it should not be your default approach.


12. Dynamic or Lazy Bean Access

If you need lazy or optional access, prefer ObjectProvider.

@Service
public class NotificationService {

    private final ObjectProvider<SmsSender> smsSenderProvider;

    public NotificationService(ObjectProvider<SmsSender> smsSenderProvider) {
        this.smsSenderProvider = smsSenderProvider;
    }

    public void notifyUser(String phoneNumber, String message) {
        SmsSender smsSender = smsSenderProvider.getIfAvailable();

        if (smsSender != null) {
            smsSender.send(phoneNumber, message);
        }
    }
}

This avoids directly depending on ApplicationContext.


13. Lazy Beans

By default, singleton beans are usually created during application startup.

You can make a bean lazy:

@Service
@Lazy
public class ExpensiveService {
}

Or inject it lazily:

@Service
public class DashboardService {

    private final ExpensiveService expensiveService;

    public DashboardService(@Lazy ExpensiveService expensiveService) {
        this.expensiveService = expensiveService;
    }
}

14. Managing Beans in Tests

In Spring tests, beans can be injected into test classes:

@SpringBootTest
class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @Test
    void placesOrder() {
        orderService.placeOrder();
    }
}

You can replace beans with mocks using Spring Boot testing support:

@SpringBootTest
class OrderServiceTest {

    @MockBean
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;

    @Test
    void placesOrder() {
        orderService.placeOrder();
    }
}

For plain unit tests, you often do not need Spring:

class OrderServiceTest {

    @Test
    void placesOrder() {
        PaymentService paymentService = mock(PaymentService.class);
        EmailService emailService = mock(EmailService.class);

        OrderService orderService = new OrderService(paymentService, emailService);

        orderService.placeOrder();
    }
}

15. Practical Rules

Use these rules most of the time:

  1. Use @Service for business logic.
  2. Use @Repository for persistence/data access.
  3. Use @Controller or @RestController for web endpoints.
  4. Use @Component for general Spring-managed classes.
  5. Use @Bean for third-party objects or special construction logic.
  6. Prefer constructor injection.
  7. Avoid field injection.
  8. Avoid calling ApplicationContext#getBean() unless you truly need dynamic lookup.
  9. Use @Qualifier or @Primary when multiple beans share the same type.
  10. Keep singleton beans stateless when possible.

Minimal Example

@Service
public class GreetingService {

    public String greet(String name) {
        return "Hello, " + name;
    }
}
@RestController
@RequestMapping("/greetings")
public class GreetingController {

    private final GreetingService greetingService;

    public GreetingController(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @GetMapping("/{name}")
    public String greet(@PathVariable String name) {
        return greetingService.greet(name);
    }
}

Spring will:

1. Find GreetingService
2. Create a GreetingService bean
3. Find GreetingController
4. Create a GreetingController bean
5. Inject GreetingService into GreetingController
6. Map GET /greetings/{name}
7. Call the controller method when a request arrives

Bottom Line

To create and manage beans in Spring:

  • annotate your classes with @Component, @Service, @Repository, or @Controller
  • define special beans with @Bean inside @Configuration
  • inject dependencies through constructors
  • let Spring manage lifecycle, scopes, configuration, and wiring

In most cases, you should declare what your application needs and let Spring create and connect the objects for you.

How do I convert Java Object to JSON?

To convert Java objects or POJOs (Plain Old Java Objects) to JSON we can use one of JSONObject constructor that takes an object as its argument. In the following example we will convert Student POJO into JSON string. Student class must provide the getter methods, JSONObject creates JSON string by calling these methods.

In this code snippet we do as follows:

  • Creates Student object and set its properties using the setter methods.
  • Create JSONObject called object and use the Student object as argument to its constructor.
  • JSONObject use getter methods to produces JSON string.
  • Call object.toString() method to get the JSON string.
package org.kodejava.json;

import org.json.JSONObject;
import org.kodejava.json.support.Student;

import java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
    }
}

Running this code produces the following result:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}

The Student class use in the code above:

package org.kodejava.json.support;

import java.util.List;

public class Student {
    private Long id;
    private String name;
    private int age;
    private List<String> courses;

    // Getters and Setters removed for simplicity
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

How do I inject beans, properties and methods using Spring EL?

Using Spring Expression Language (SpEL) we can inject object references or values into a bean dynamically when the bean is created instead of statically defined at development time. In this example you’ll learn how to inject a bean’s property using a property of another bean.

Let start by create two classes, the Student and Grade classes. The student object will have a property to store their grade name which will be obtained from the grade object.

package org.kodejava.spring.core.el;

public class Student {
    private String name;
    private String grade;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}
package org.kodejava.spring.core.el;

public class Grade {
    private String name;
    private String description;

    public Grade() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Next we create the spring configuration file. In this configuration we have two beans definition, the grade and student bean. We set the name and description property of the grade bean.

We also set the name property of student bean using a string literal. But the grade property value is set to the grade‘s bean name property using the Spring EL, #{grade.name}. The expression tells the spring container to look for a bean whose id is grade, read its name and assign it to student‘s grade.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="grade" class="org.kodejava.spring.core.el.Grade">
        <property name="name" value="Beginner" />
        <property name="description" value="A beginner grade." />
    </bean>
    <bean id="student" class="org.kodejava.spring.core.el.Student">
        <property name="name" value="Alice" />
        <property name="grade" value="#{grade.name}" />
    </bean>

</beans>

And then create the following program to execute the spring container and retrieve the student bean from it.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELDemo {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-example.xml")) {

            Student student = (Student) context.getBean("student");
            System.out.println("Name  = " + student.getName());
            System.out.println("Grade = " + student.getGrade());
        }
    }
}

This program will print the following output:

Name  = Alice
Grade = Beginner

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How to set and get properties of a bean in JSP?

In this example you will learn how to set and get the value of Java object properties that you define in a JSP pages. For this example, let’s first start by creating a variable that we named customer, that will have a type of Customer class. To create this variable we use the <jsp:useBean> action.

After we create the customer variable we can set the property value of the customer bean using the <jsp:setProperty> action. And to get the property value of the customer bean we use the <jsp:getProperty> action.

The name attribute in the setProperty and getProperty action refer to our customer bean. The property attribute tells which property we are going to set or get. To set the value of a property we use the value attribute.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Bean Property Demo</title>
</head>
<body>

<jsp:useBean id="customer" class="org.kodejava.servlet.support.Customer"/>
<jsp:setProperty name="customer" property="id" value="1"/>
<jsp:setProperty name="customer" property="firstName" value="John"/>
<jsp:setProperty name="customer" property="lastName" value="Doe"/>
<jsp:setProperty name="customer" property="address" value="Sunset Road"/>

Customer Information: <%= customer %><br/>
Customer Name: <jsp:getProperty name="customer" property="firstName"/>
<jsp:getProperty name="customer" property="lastName"/>

</body>
</html>

And here is the code for our Customer bean. This bean contains property such as the id, firstName, lastName and address.

package org.kodejava.servlet.support;

public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String address;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

We access the JSP page we will see the following output:

Customer Information: Customer{id=1, firstName='John', lastName='Doe', address='Sunset Road'}
Customer Name: John Doe
JSP Bean Property Demo

JSP Bean Property Demo

How do I define inner bean in Spring?

Inner bean is a bean defined inside another bean, it can be seen as an inner class. In another word, the inner bean is a bean defined within the scope of another bean. In this case the inner bean can only be use by the outer bean. No other bean in the Spring context can refer to that bean.

So, if you sure that a bean is only use within a single bean it is a good idea to use an inner bean. Inner bean can be injected through setter injection or constructor injection.

Here is an example of Spring configuration for an inner bean injection:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="racer" class="org.kodejava.spring.core.Racer">
        <property name="car">
            <bean class="org.kodejava.spring.core.Car">
                <property name="maker" value="Ferrari" />
                <property name="year" value="2021" />
            </bean>
        </property>
    </bean>

</beans>

In this configuration we use a setter injection. So we use the property element. Instead of using a ref attribute for referring to another bean we define the bean using the bean element inside the property element. And then we create the Car bean and sets its properties.

If you want to use a constructor injection you can inject the Car bean into the Racer bean by defining a bean inside the constructor-arg element in the Racer bean.

Below is our Racer and Car classes.

package org.kodejava.spring.core;

public class Racer {
    private Car car;

    public Racer() {
    }

    public Racer(Car car) {
        this.car = car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Racer{" +
                "car=" + car +
                '}';
    }
}
package org.kodejava.spring.core;

public class Car {
    private String maker;
    private int year;

    public void setMaker(String maker) {
        this.maker = maker;
    }

    public void setYear(int year) {
        this.year = year;
    }

    @Override
    public String toString() {
        return "Car{" +
                "maker='" + maker + "'" +
                ", year=" + year +
                '}';
    }
}

Let’s create our Demo class to run the program:

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
    public static void main(String[] args) {
        var context = new ClassPathXmlApplicationContext("inner-bean.xml");

        Racer racer = (Racer) context.getBean("racer");
        System.out.println("Racer = " + racer);
        context.close();
    }
}

Here is the output of our program:

Racer = Racer{car=Car{maker='Ferrari', year=2021}}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central