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
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
Application configuration
- Java
- Annotations
- XML (still available but heavy)
@ComponentScan("fr.sii.cheatsheet.spring")
public class MyApp {
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(MyApp.class);
DummyService helloWorld = app.getBean(DummyService.class);
helloWorld.getMessage();
}
}
Prefer use of a configuration class
@Configuration
public class MyAppConfig {
// @Bean, ...
}
Dependency injection
Define a bean : @Bean
@Configuration
public class MyAppConfig {
@Bean
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
@Component
public class DummyServiceImpl implements DummyService {
}
Dependency injection : @Autowired
- Via a class field
- Via a setter
- Via the constructor (prefer for easy test)
@Component
public class FooServiceImpl implements FooService {
@Autowired
private DummyService service;
@Autowired
public FooServiceImpl(DummyService dummyservice) {
this.service = dummyService;
}
@Autowired
public DummyService setDummyService(DummyService dummyService) {
this.service = dummyService;
}
}