12. SpringBoot
- Convention over configuration solution
- Standalone applications (JAR)
- Embedded application servers (no WAR)
- Simplified and auto configuration
- Starters
- Production-ready features
- Metrics
- Health check
- Externalized config
- No code generation
- No XML config required
13. plugins {
id 'org.springframework.boot' version '2.1.4.RELEASE'
}
apply plugin: 'io.spring.dependency-management'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
Starters
Spring Initializr
14. IoC & DI
- Inversion of Control
- Creationg of objects is transferred to a container or framework
- Decouples execution of tasks from their implementations
- Improves modularity (different implementations)
- Improves testability (isolating and mocking components)
- Dependency Injection
- Pattern that implements IoC principle
- Control being inverted is setting of objects' dependencies
15. public class UserService {
private final UserRepository repository;
public UserService() {
this.repository = new UserRepositoryImpl();
}
}
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
}
IoC & DI
17. BeanFactory & ApplicationContext
- BeanFactory
- Container for managing beans
- Resolve object graphs
- XML vs Annotation-based DI
- Component scanning
- ApplicationContext
- Central interface for configuration
- Builds on top of BeanFactory
- Loads file resources
- Publishes lifecycle events to
registered listeners
- Resolves messages for
internationalization
18. XML vs Annotation-based DI
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="<tl;dr>"
xmlns:xsi="<tl;dr>"
xmlns:context="<tl;dr>"
xsi:schemaLocation="<tl;dr>">
<bean id="userRepository"
class="io.townsq.es.day.UserRepositoryImpl"/>
<bean id="userService"
class="io.townsq.es.day.UserService">
<constructor-arg ref="userRepository"/>
</bean>
</beans>
@Configuration
public class BeanConfiguration {
@Bean
public UserRepository userRepository() {
return new UserRepositoryImpl();
}
@Bean
public UserService userService(UserRepository repo) {
return new UserService(repo);
}
}
19. Component Scanning & Auto-wiring
@Repository
public class UserRepositoryImpl implements UserRepository {
}
@Service
public class UserService {
private final UserRepository repository;
@Autowired
public UserService(UserRepository repository) {
this.repository = repository;
}
}
22. Java Servlet
- Java class that
- Handles and processes requests
- Replies a response back
- Managed by Servlet containers
- Application servers
Web Server
JVM
Servlet
Container
Servlet
init()
service()
destroy()
Thread A
Thread B
Request to
Server
23. HTTP Servlet
@WebServlet(urlPatterns = "/users/*")
public class UserServlet extends HttpServlet {
private final UserService userService = new UserService(new UserRepository() {});
private final ObjectMapper mapper = new ObjectMapper();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userId = request.getPathInfo().split("/")[1];
User user = userService.getUserById(userId);
response.setContentType("application/json");
response.getWriter().print(mapper.writeValueAsString(user));
response.getWriter().flush();
}
}
24. MVC in JEE
Client
Controller
Model
View
Request processing
Data validation
Business logic
Data manipulation
Response generation
Rendering
Database
Servlet
JSP
Bean
Request
Response
Browser
25. Spring MVC
- Web framework built on top of Servlet API
- Request routing and handling
- Object marshalling and validation
- Error handling
Controller
Model
View
Endpoints
JSON
Services
Database
Repositories
26. Controller @RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public User getUserById(@PathVariable Integer userId) {
return service.getUserById(userId);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@RequestBody User user) {
return service.createUser(user);
}
@GetMapping
public Collection<User> listUserByLastName(@RequestParam String lastName) {
return service.listUserByLastName(lastName);
}
}
27. Error Handling
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorMessage handle(IllegalArgumentException exception) {
return new ErrorMessage(exception.getMessage());
}
}
28. JPA
- Specification that describes management of relational data
- Entities:
- Lighweight Java class whose state is persisted to a table in a relational database
- Implementations:
- Hibernate, TopLink, OpenJPA, Spring Data JPA
29. ORM
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(250) NOT NULL,
first_name VARCHAR(250) NOT NULL,
last_name VARCHAR(250) NOT NULL,
birth_date DATE NOT NULL
);
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, unique = true)
private String email;
private String firstName;
private String lastName;
private LocalDate birthDate;
}
30. Hibernate
public class UserDao {
public User getById(Integer id) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
User user = session.get(User.class, id);
session.close();
return user;
}
}
31. Spring Data JPA
- Collection of default interfaces that gives
- Most common CRUD operations
- Sorting and paginating features
- Automatic custom querying
- Query DSL for extending query capabilities
- Custom querying with named queries
32. JPA with Spring Data
public interface UserRepository extends CrudRepository<User, Integer> {
Optional<User> findByEmail(String email);
Collection<User> findAllByLastName(String lastName);
}
public class UserService {
public void doSomething() {
Collection<User> users = repository.findAllByLastName("Banner");
Optional<User> user1 = repository.findByEmail("banner@townsq.io");
Iterable<User> all = repository.findAll();
Optional<User> user2 = repository.findById(1);
User saved = repository.save(new User());
repository.deleteById(2);
}
}
33. Next Steps
- Spring Security
- Customizable
- Authentication
- Authorization (access control)
- Spring Data with No-SQL
- Mongo
- ElasticSearch
- Cassandra
- Redis
- Spring Webflux
- Functional routing and handling
- Reactive components
- Event loop concurrency model
- Netty
- Reactor
34. Next Steps
- Spring Cloud
- Cloud-native applications
- Microservices
- Netflix OSS
- Externalized configuration
- Service discovery
- Gateway
- Resilience
- Streams
- Spring with other JVM langs
- Groovy
- Kotlin