The Java Spring Framework is a library whose core job is to create your application's objects and connect them to each other, so your classes do not construct their own collaborators. The objects it manages are called beans, and the mechanism that hands them their dependencies is called dependency injection.
This article covers the core of the framework: what the container is, what a bean is, the three ways to inject a dependency, how Spring finds your classes, and what bean scopes mean. Everything here comes from the Spring Framework reference documentation. If you want to run something right away, the Spring Boot tutorial for beginners builds a working web app, and Boot uses all of the ideas below.
What the Spring Framework is
Spring is a large project with many modules: web MVC, data access, testing support and more. All of them sit on one foundation, the inversion of control (IoC) container. The reference states that dependency injection is a specialized form of IoC, "whereby objects define their dependencies only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed". The container then injects those dependencies when it creates the bean.
The effect is that a class says what it needs, and something else decides where it comes from. A service class asks for a repository in its constructor. It never writes new JpaRepository() itself. That makes the class easier to test, because a test can pass in a fake repository, and easier to change, because swapping the implementation does not touch the service.
What is a bean?
The reference defines it precisely: a bean is an object that is instantiated, assembled and managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Nothing about the class itself is special. What makes it a bean is that you registered it with the container, either through configuration or through annotations the container scans for.
The container: BeanFactory and ApplicationContext
Two interfaces represent the container. BeanFactory provides the configuration framework and basic functionality. ApplicationContext is a sub-interface that adds easier integration with Spring's AOP features, message resource handling for internationalization, event publication, and application-layer contexts such as WebApplicationContext. The reference says ApplicationContext is a complete superset of BeanFactory, and in practice you work with ApplicationContext.
In a plain Java program you can create one from a Java configuration class and ask it for a bean:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service = context.getBean(MyService.class);
In a Spring Boot application you rarely write this, because Boot creates the context for you when main calls SpringApplication.run. The container still exists, and it still builds and wires your beans.
Three ways to inject a dependency
Constructor injection
The class declares its dependencies as constructor parameters:
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) {
this.repository = repository;
}
}
The Spring documentation says the team generally advocates this style, "as it lets you implement application components as immutable objects and ensures that required dependencies are not null". It also notes that constructor-injected components are always returned to the calling code in a fully initialized state. Its rule of thumb is to use constructors for mandatory dependencies and setter methods for optional ones. The reference adds that a long list of constructor arguments is "a bad code smell", a sign the class probably does too much.
You do not need @Autowired here. The autowiring page states that an @Autowired annotation on a constructor is not necessary if the target bean defines only one constructor. If a class has several constructors and no default one, at least one must carry @Autowired so the container knows which to use.
Setter injection
The container creates the object first, then calls setter methods. The reference recommends it for optional dependencies that have a sensible default. A setter can also be called again later, which makes the object easier to reconfigure.
Field injection
You can put @Autowired directly on a private field. It is short, but the class can then only be created correctly by the container or by reflection, and the dependency is not visible in the constructor. The reference's recommendations favor constructors, so use field injection sparingly if at all.
How Spring finds your classes
There are two ways to register a bean: scan for annotated classes, or declare it in a configuration class.
Stereotype annotations and component scanning
@Component is the generic stereotype for any Spring-managed component. @Repository, @Service and @Controller are specializations of it for the persistence, service and presentation layers. The reference says @Service is clearly the better choice than @Component for a service-layer class, and that @Repository also enables automatic translation of persistence exceptions.
The container only finds these classes if scanning is switched on and pointed at the right package:
@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig {
}
By default the detected candidates are classes annotated with @Component, @Repository, @Service, @Controller, @Configuration, or a custom annotation that is itself annotated with @Component. The default bean name is the uncapitalized, non-qualified class name, so MovieFinderImpl becomes movieFinderImpl. In Spring Boot, @SpringBootApplication turns on scanning for its own package and sub-packages, which is why a class in an unrelated package is silently never registered.
@Configuration and @Bean
For classes you cannot annotate, such as ones from a library, write a factory method instead:
@Configuration
public class AppConfig {
@Bean
public BeanOne beanOne() {
return new BeanOne(beanTwo());
}
@Bean
public BeanTwo beanTwo() {
return new BeanTwo();
}
}
Here beanOne gets its BeanTwo through constructor injection. The reference points out a subtlety: all @Configuration classes are subclassed at startup with CGLIB, and the subclass checks the container for an existing bean before calling the method. That is why calling beanTwo() twice still gives one shared instance. It also says you cannot declare inter-bean dependencies this way in plain @Component classes. If you set @Configuration(proxyBeanMethods = false) to skip the proxying, calls between bean methods are no longer intercepted, so pass dependencies in as method parameters instead.
Bean scopes
The default scope is singleton: one object instance per container for each bean definition. That matters for design. A singleton bean is shared by every caller, including many threads in a web app, so it should not hold per-request state in its fields.
| Scope | Meaning | Needs a web-aware context? |
|---|---|---|
singleton (default) | One instance per container | No |
prototype | A new instance each time the bean is requested | No |
request | One instance per HTTP request | Yes |
session | One instance per HTTP session | Yes |
application | One instance per ServletContext | Yes |
websocket | One instance per WebSocket session | Yes |
Using a web scope in a non-web container, such as ClassPathXmlApplicationContext, throws an IllegalStateException, according to the reference.
Common errors and what they mean
BeanCurrentlyInCreationException. Two beans need each other through their constructors. The reference says the container detects the circular reference at runtime and throws this exception. The suggested fix is to redesign so the cycle disappears, or use setter injection for one side. The reference calls circular dependencies configured through setters "not recommended".- A bean is never found. The class is probably outside the scanned packages, or it has no stereotype annotation. Check the package of your
@ComponentScanor@SpringBootApplicationclass. - Several beans of the same type. Injection by type becomes ambiguous. The reference describes
@Primaryand qualifiers on separate pages, so read those before choosing between them. - Per-user data leaking between requests. A singleton holds state in a field. Move the state into a method, or give the bean a request or session scope.
Where to go next
Write a small program with AnnotationConfigApplicationContext and two beans, where one depends on the other, before moving to Boot. Seeing the container work without auto-configuration makes the Boot startup log much easier to read. If you are still deciding whether Java is the right language for your project, Java vs Python: the differences side by side compares them.
Frequently asked questions
- What is the difference between Spring Framework and Spring Boot?
- The Spring Framework is the core library: the container, dependency injection, web MVC and data access support. Spring Boot sits on top of it and chooses defaults for you through starter dependencies and auto-configuration, so you write less setup code. Boot applications still use the Spring Framework container underneath.
- What is a bean in Spring?
- According to the Spring reference, a bean is an object that is instantiated, assembled and managed by a Spring IoC container. Any other object in your program that the container does not manage is just an ordinary object.
- Is constructor injection better than field injection?
- The Spring documentation advocates constructor injection because it lets you make components immutable and guarantees that required dependencies are not null. Field injection hides the dependencies and makes the class harder to create in a plain unit test without the container.
- What is the default scope of a Spring bean?
- Singleton. The container creates one shared instance of the bean definition per container, and every injection point gets that same object. Use the prototype scope if you need a new instance on each request for the bean.
Sources
- Spring Framework reference: Introduction to the Spring IoC Container and Beans
- Spring Framework reference: Dependency Injection
- Spring Framework reference: Bean Scopes
- Spring Framework reference: Classpath Scanning and Managed Components
- Spring Framework reference: Using @Autowired
- Spring Framework reference: Using the @Configuration annotation