Andrez Segovia

Working with Beans in Spring Framework

Published on • • 297 Words

A JavaBean is a standard Java class with getter/setter methods, a no-arg constructor, and is serializable. And a Spring Bean is any Java object managed by Spring and can be automatically injected into other components. The Spring Dependency injection allows Spring to manage and inject beans where needed.

Creating a bean

We can create beans with Spring Framework as follows:

Using @Component Annotation

1import org.springframework.stereotype.Component;
2
3@Component
4public class UserService {
5    public String getUserName() {
6        return "john.doe";
7    }
8}

Using @Bean inside a @Configuration class

 1import org.springframework.context.annotation.Bean;
 2import org.springframework.context.annotation.Configuration;
 3
 4@Configuration
 5public class AppConfig {
 6
 7    @Bean
 8    public UserService userService() {
 9        return new UserService();
10    }
11}

Using XML-based bean definition

1<bean id="userService" class="com.example.UserService"/>

This approached was used before the annotations implementation.

Using a bean

Once a class is defined as a bean, it can be injected into other components/beans using the @Autowired annotation.

 1import org.springframework.beans.factory.annotation.Autowired;
 2import org.springframework.stereotype.Service;
 3
 4@Service
 5public class Service {
 6
 7    private final UserService userService;
 8
 9    @Autowired
10    public Service(UserService userService) {
11        this.userService = userService;
12    }
13
14    public void printUserName() {
15        System.out.println(userService.getUserName());
16    }
17}

Bean scopes

By default, all beans in Spring Framework have a Singleton scope (one instance per spring container), but we can change their scope.

The following are the scopes a bean can has:

ScopeDescription
SingletonDefault. A single instance is created and shared.
PrototypeA new instance is created every time the bean is requested.
RequestA new instance is created per HTTP request (for web apps).
SessionA new instance is created per user session (for web apps).

The scope can be change with the @Scope annotation:

1import org.springframework.context.annotation.Scope;
2import org.springframework.stereotype.Component;
3
4@Component
5@Scope("prototype")
6public class PrototypeBean {
7    // Bean logic here
8}