Spring core cheat sheet
Container, Dependency and IOC

Spring 5.3.21+ - Date : August 2022

What is Spring ?

  • Open source (Apache 2 licence, sources on github)
  • Light
    • Doesn't force to use an application server
    • Not invasive
  • Container
    • Application objects doesn't have to look for their dependencies
    • Handles objects life cycle
  • Framework
    • Ease integration and communication with third-party libraries

Minimal dependencies


Application configuration

  • Java
  • Annotations
  • XML (still available but heavy)
public class MyApp {

    public static void main(String[] args) {
        ApplicationContext app = new AnnotationConfigApplicationContext(MyApp.class);

        DummyService helloWorld = app.getBean(DummyService.class);

Prefer use of a configuration class

public class MyAppConfig {
  // @Bean, ...

Dependency injection

Define a bean : @Bean

public class MyAppConfig {
  public DummyService dummyService(){
    return new DummyServiceImpl();

Define a bean : @Component

@Component specializations :

  • @Service : Heart of an app
  • @Repository : Handles data persistence
  • @Controller : Handles requests and reponses
public class DummyServiceImpl implements DummyService {

Dependency injection : @Autowired

  • Via a class field
  • Via a setter
  • Via the constructor (prefer for easy test)
public class FooServiceImpl implements FooService {

  private DummyService service;
  public FooServiceImpl(DummyService dummyservice) {
    this.service = dummyService;
  public DummyService setDummyService(DummyService dummyService) {
    this.service = dummyService;


Beans scopes

Scope Description
singleton (default) A single bean instance
prototype A bean instance per usage
request A bean instance per HTTP request
session A bean instance per HTTP session
application A bean instance per Servlet Context
websocket A bean instance per WebSocket

Customizing a bean

Initialization method


Destroy method


SpEL : Spring Expression Language

Access a system properties

@Value("#{ systemProperties['user.home'] }")
private String defaultHome;

Access a bean property

private String myValue;

Parse a string

private String myValue;


@Value("#{myBean.myValue.length() > 2}")
private String myValue;


 * File 'foo.properties' loaded by Spring
public class MyAppConfig {

   * Property max in file foo.properties.
  private Integer max;

Use a property : @Value("${message}")

@Value("${message:Default message}")
private String message;

Go deeper