- What is Spring Framework?
- What is a Spring Bean?
- Annotations
- Dependency Injection
- Bean Scoping
- Special Spring Environment
- @Value Annotation
- Best Practices
- Spring Boot
The Spring Framework is lightweight open source project for building enterprise Java Apps. Aims to simplify complexities that come with an enterprise Java apps.
-
IoC (Inversion of Control): Provides a streamlined way to configure and manage Java objects. The framework is responsible of the life cycle of the defined Java object. Use Dependency Injection to provide the object reference during runtime.
-
AOP (Aspect Oriented Programming): Provide more modularity, login, cashing, authentication, etc.
-
DAF (Data Access Framework): Simplifies the database communication proccess, by providing direct support for poppular data access framework in Java, like JDBC, Hibernate, JPA Api.
-
MVC: Allow us to easy create projects with the MVC pattern.
An Spring Bean is an object managed (life cycle, org. dependecies) by the Spring Framework. Spring beans could be configured using xml, Java annotations or Java code. "In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container."
@Qualifier lets us tell Spring which bean to inject. If we don't use it, we may have ambiguity problems with the beans
Nevertheless we can use the @Primary annotation to disambiguate and set 1 bean as a primary bean
@Configuration declares class as full configuration class
@Bean declares bean configuration class. If we put @Bean("examplename") now the name for that Bean is examplename instead of the name of the method
@Configuration
class VehicleFactoryConfig {
@Bean
Engine engine() {
return new Engine();
}
}
@Component marks a class as an Spring Component. As a general component annotation indicates that the class should be initialized, configured and managed by the core container
@Repository annotates classes at the persistence layer, will act as a database repository
@Service annotates classes to indicate that they are holding business logic.
@Controller annotates classic controllers and its typically use with @RequestMapping. Is a specialization of the @Component
@RestController is equivalent than a class with @Controller and @ResponseBody annotation. Every request handling method of the controller class automatically serializes return objects into HttpResponse.
Constructor-dependency injection is automatically done using @Autowired, by injecting the constructor paramenter/s
@Autowired on Constructior is optional if there is only one constructor
Spring Framework provides 4 ways to inject Beans
- Constructor: During bean construction
- Field (Not recommended, only for test)
- Configuration: Configuration Methods
- Setter: Setter Methods Injection
Example without DI
public class Store {
private Item item;
public Store() {
item = new ItemImpl1();
}
}
Example with DI (Constructor Injection)
public class Store {
private Item item;
public Store(Item item) { // We dont know the object implementation
this.item = item;
}
}
Example with DI (Method Injection)
@Service
public class DefaultPaymentService{
@Autowired
public void configureClass(
AccountRepository accountRepository,
FeeCalculator feeCalculator
){
// Some fancy code
}
}
-
Bean Scope: Life cycle of a Spring Bean and its availability in the context of the app.
-
Multiple scopes:
-
Life cycle of a Spring Bean (Managed by the Spring Container)
- SINGLETON: This is the default scope, the Spring Container only creates 1 instance and all requests for that bean name will return the same object. Any modifications to this object will be reflected in all references to the bean
- PROTOTYPE: A bean with prototype scope will return a different instance every time it is called. It is defined by setting the value prototype to the @Scope("prototype") annotation
- REQUEST: The bean is created for each HTTP request
- SESSION: The bean is created for each HTTP session
- APPLICATION: It is similar to the Singleton scope. In this case, the same instance of the bean is shared across multiple servlet-based applications running in the same ServletContext, while singleton scoped beans are scoped to a single application context only.
- WEBSOCKET: Similar to Singleton scope but limited to a WebSocket session only
Example of Application Scope
@Bean
@ApplicationScope
public HelloMessageGenerator(){
applicationScopedBean() {
return new HelloMessageGenerator();
}
}
-
Environment: We can consider each stage of the app (development/testing/etc) as an environment. In each stage we need a specific environment to work with.
Sometimes we need to disable some functionalities/infrastructure of the app such as logging, etc. To make this happen, we can group bean definitions based on the profile name (Using @Profile("name") / we can also do this coding with the use of AnnotationConfigApplicationContext / in the application.properties).
Example of Environment
@Configuration
public class AplicationConfig{
@Autowired
final Environment environment;
@Bean
public PaymentService paymentService(){
var profile = Profiles.of("cloud");
var isOkay = this.environment.acceptsProfiles(profile);
this.environment.getProperty("data.driver");
return ...
}
}
Example of Profile
@Service
@Profile("cloud")
public class DefaultPaymentService implements PaymentService{}
This annotation is commonly used to inject values into a variable, no matter the type.
Example of use
@Configuration
@PropertySource("classpath:database.properties") //Our source for @Value
public class ApplicationConfig{
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Bean
public DataSource dataSource(){
return ...;
}
}
Example
@Configuration
public class ServiceConfig{
@Bean
public PaymentService paymentService(){return new ...}
}
@Configuration
public class RepositoryConfig{
@Bean
public AccountRepository accountRepository(){return new ...}
}
@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
public class AppConfig{
@Bean
public DataSource dataSource(){ ... }
}
- Spring boot is an approach to develop Spring based apps with very little to no configurations.
- Spring boot provides a set of starter
- Standalone Apps
- Embedded Server (Such as Tomcat or Jetty)
- Starters
- Auto Configuration
- Production Ready Feature
- No Xml configuration