Thus far we have discussed several essential things about object instances managed by Spring (beans). We covered the important syntaxes you need to know to create beans, and we discussed establishing relationships among beans (including the necessity of using abstractions). But we didn’t focus on how and when Spring creates the beans. From this perspective, we’ve only relied on the framework’s default approaches.

Spring has multiple different approaches for creating beans and managing their life cycle, and in the Spring world we name these approaches scopes. In this chapter, we discuss two scopes you’ll often find in Spring apps: singleton and prototype. Singleton is the default scope of a bean in Spring, and it’s what we’ve been using up to now.

Using the singleton bean scope

The singleton bean scope defines Spring’s default approach for managing the beans in its context. It is also the bean scope you’ll most encounter in production apps.

Spring creates a singleton bean when it loads the context and assigns the bean a name (sometimes also referred to as bean ID). We name this scope singleton because you always get the same instance when you refer to a specific bean. But be careful! You can have more instances of the same type in the Spring context if they have different names:

Untitled

DECLARING SINGLETON-SCOPED BEANS WITH @BEAN

0oce9806.bmp

As you can see, the coffee bean in the visual represents the instance that Spring adds to its context. Observe that the context contains only one instance (coffee bean) with an associated name.

4sch93jp.bmp

In this example, I used the @Bean annotation approach to add the bean to the Spring context. But I don’t want you to think a singleton bean can only be created using the @Bean annotation. The result would have been the same if we used stereotype annotations (like @Component) to add the bean to the context.

Running the Main class in thee image above will print “true” in the console because, being a singleton bean, Spring returns the same reference every time.

DECLARING SINGLETON BEANS USING STEREOTYPE ANNOTATIONS

As mentioned earlier, Spring’s behavior for singleton beans isn’t any different when using stereotype annotations than when you declared them with the @Bean annotation. But in this section, I’d like to enforce this statement with an example.

Consider a class design scenario where two service classes depend on a repository. Say we have both CommentService and UserService depending on a repository named CommentRepository:

d95mfbxi.bmp

A visual representation of the context near the code that configures it:

e1p4cwtx.bmp

Additionally to the code above, we also have a configuration class:

@Configuration
@ComponentScan(basePackages = {"services", "repositories"})
public class ProjectConfig {

}