Training - Spring

Last Updated on: August 11, 2021 pm

Spring

Dependency Injection

Allows one Java Object to be ==*Injected*== into as another Object as a property.

Three ways to Wire Objects

Java Configuration Class

A Java class is created that acts as the configuration

- Creating and then wiring the two objects together

  • The ==@Configuration== annotation specifies that this class is acting as a configuration class
  • The ==@Bean== is used to show that a method is returning a bean available within the context
  • ==@Autowired== is used to say that the Pet for the person must be automatically wired from another @Bean somewhere

Example:

A pet is injected into person object as a property using ==Java Configuration==.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class PersonConfiguration {

@Bean
public Pet pet(){
return new Cat();
}

@Bean
public Person person(
@Autowired Pet pet){
return new Person(pet);
}
}

How to use the Configuration

A configuration was loaded using ApplicationContext

Annotations

XML Files

Application Context or XML Bean Factory?

Spring provides two kinds of IOC Container -

  • XML BeanFactory
  • ApplicationContext

Use ApplicationContext unless you have a really good reason not doing so.

Example:

1
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfiguration.class);

Singleton

1
2
Person person = context.getBean(Person.class);
Person person2 = (Person)context.getBean("person");

Layered Architectures

Controller Layer

Receive requests from client applications

Service Layer

Business layer with business functions

Data Access Layer

Two Patterns: - Used Interchangeably

  • Data Access Object
  • Repository

Data Access/Repository Pattern

The pattern involves classes that carry out database access on behalf of data structures

Each Data structure has a corresponding Data Access Object

More Pattern - DTO

Data Transfer Object (DTO)

  • A DTO is a structure that can be used within the application itself
  • The DTO is converted to and from the database specific Entity class by the data layer
  • This decouples the rest of the application from any database specific class structures