Java Web Programming 420-N34-LA F2023 PDF

Document Details

Uploaded by Deleted User

2023

Christine Gérard

Tags

Java programming Spring web programming

Summary

These are lecture notes regarding Java Web Programming, focusing on Inversion of Control (IoC) containers and Dependency Injection (DI) patterns specifically within the Spring framework. The provided notes cover different related concepts and show relevant examples.

Full Transcript

Java Web Programming 420-N34-LA F2023 Week 1 – Inversion of Control Containers & Dependency Injection Pattern Copyright @ 2023 by Christine Gérard Agenda 1. Inversion of Control 2. Spring Beans 3. Dependency Injection Pattern 4. DI Walkthrough 5. DI: Spring Annot...

Java Web Programming 420-N34-LA F2023 Week 1 – Inversion of Control Containers & Dependency Injection Pattern Copyright @ 2023 by Christine Gérard Agenda 1. Inversion of Control 2. Spring Beans 3. Dependency Injection Pattern 4. DI Walkthrough 5. DI: Spring Annotations and Examples 6. Hands-On Class Activity: DI Activity 7. Homework 8. What’s next? 2 1 Inversion of Control Container Inversion of Control ⦿ A pattern that defines how components from different projects are assembled into a cohesive application ⦿ The application cedes control of this assembly to the container or framework 4 Inversion of Control in Spring ⦿ In the Spring Framework, the IoC container is represented by the ApplicationContext interface ⦿ The Spring container is responsible for instantiating, configuring and assembling objects (aka beans), as well as managing their lifecycles 5 2 Beans Java Bean A Java class that has the following characteristics: ⦿Has a public no-arg constructor ⦿Is serializable (implement java.io.Serializable) ⦿Has setters and getters for its properties 8 Java Bean ≠ Spring Bean 9 Spring Beans and the Spring Inversion of Control (IoC) Container A Spring Bean is an object managed by the Spring IoC Container ⦿ A Spring Bean can be instantiated, configured, and otherwise managed by the Spring IoC Container ⦿ A Spring Bean is defined by using Spring Annotations, instantiated by the Spring IoC Container, and then injected into your application 10 Spring Bean Spring can manage almost any object, even one that doesn’t have the Java Bean characteristics. 11 Spring Bean Scope Spring Framework currently defines 6 types of scope for Spring beans: @Scope("singleton") ⦿ Singleton (default) Or @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) ⦿ Prototype For web-aware applications only: ⦿ Request ⦿ Session ⦿ Application ⦿ Websocket 12 Why do we care about Spring Beans? ⦿ They are an integral aspect of Dependency Injection 13 3 Singletons In Spring IoC Container Singleton Design Pattern ⦿ A pattern to create a class that only allows a single instance of itself to be created, and usually gives simple access to that instance. ⦿ Constructor parameters are usually not allowed GoF Singleton Design Pattern ⦿ Creational pattern – control class instantiation ⦿ Used when there should only be one instance of a given class. ⦿ All future references to objects of the singleton class refer to the same underlying instance. Source: https://www.gofpatterns.com/design-patterns/module3/intro-singleton-design-pattern.php GoF Singleton Design Pattern ⦿ The only public access is the static GetSingleton method. ⦿ GetSingleton returns the single instance of the class ⦿ The single instance of the class is held in the private reference variable called instance. (Usually, we implement this as a static variable). ⦿ The constructor, Singleton, is private. Source: http://www.blackwasp.co.uk/Singleton.aspx Singleton Requirements - Java 1. A single constructor that is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime. 18 Singleton Requirements - Java 2. A private static variable which holds a reference to the single created instance, if any. 3. A public static means of getting the reference to the single created instance, creating one if necessary. Note: in C#, the class needs to be sealed, which also prevents inheritance/sub-classing. Singleton – Simple Example public class SingletonClass { Note that the constructor of the private static SingletonClass instance = null; SingletonClass class is made private to make sure that there is private SingletonClass() { no other way to instantiate the } class. public static SingletonClass getInstance() { This example is known as lazy if (instance == null) { initialization – which means that it instance = new SingletonClass(); restricts the creation of the } instance until it is requested for the return instance; first time. } } 20 Singleton – Eager Initialization This approach is similar to the lazy implementations, with the difference that this one always creates an instance, even if one is not currently necessary public class SingletonClass { in the program. This might be considered a bad practice, but it’s suitable for private static final SingletonClass INSTANCE = new SingletonClass(); situations where the creation of the instance is not too expensive or private SingletonClass() {} demanding. This is useful when the cost of creating the object is not significant or when you know your application will always instantiate the class. public static SingletonClass getInstance() { return INSTANCE; Note that the final keyword here enables the class to actually be a singleton, i.e. } ensures that only one instance exists. } 21 Singleton - Thread-safe public class SingletonClass { //synchronized method to control simultaneous access synchronized public static SingletonClass getInstance() private static SingletonClass instance; { if (instance == null) private SingletonClass() { } { // if instance is null, initialize instance = new SingletonClass(); } return instance; } } 22 Bean Scope in Spring Boot Scope Description singleton (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. prototype Scopes a single bean definition to any number of object instances. request Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext. websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext. Source: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes 23 The Singleton Bean Scope in Spring ⦿ Only one shared instance of a singleton bean is managed, and all requests for beans with an ID or IDs that match that bean definition result in that one specific bean instance being returned by the Spring container. 24 The Singleton Bean Scope in Spring ⦿ To put it another way, when you define a bean definition and it is scoped as a singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. ⦿ This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object. 25 The Singleton Bean Scope in Spring 26 The Singleton Bean Scope in Spring ⦿ Spring’s concept of a singleton bean differs from the singleton pattern as defined in the Gang of Four (GoF) patterns book. ⦿ The GoF singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. ⦿ The scope of the Spring singleton is best described as being per- container and per-bean. This means that, if you define one bean for a particular class in a single Spring container, the Spring container creates one and only one instance of the class defined by that bean definition. 27 4 Eager vs Lazy Initialization Default – Eager Initialization ⦿ By default in Spring, defined beans and their dependencies are created when the application context is created. This is eager initialization. ⦿ If we want lazy initialization – ie. That the bean and its dependencies be created only when needed—we need to inform the IoC container of this. 30 5 Dependency Injection Pattern What is dependency injection? ⦿ In our programs, we have classes. Those classes have dependencies. ⌾ Whose responsibility is it to create these dependencies? ⌾ How do we get those dependencies? 32 Example ⦿ Set-up ⌾ Assume we have a Garage class that has a dependency on a Manager class. ⌾ As cars arrive at the Garage (i.e. requests), the Manager is called to schedule the requests. ⌾ The Manager class has a dependency on the Scheduler class. ⦿ Whose job is it to create an object of the Manager class? What about the Scheduler class? ⦿ Do we want there to be multiple instances of these classes? If not, who controls that? 33 Example cont’d ⦿ Scenario 1: No Inversion of Control ⌾ It would be each class's responsibility to create and manage their own dependencies. ⌾ If we only want to have one instance, then we have a problem. Maybe the app’s “main” class has to own these dependencies. ⦿ Scenario 2: Inversion of Control Container ⌾ It would be the IoC container’s responsibility to create and manage these dependencies ⌾ Each class would tell the IoC container that it needs to use a particular dependency using Dependency Injection ⌾ If we want only to have one instance, no problem! The IoC container will handle that for us! 34 Dependency Injection – Example from M. Fowler Traditional – Scenario 1 With IoC & DI – Scenario 2 Source: https://martinfowler.com/articles/injection.html 35 Dependencies ⦿ Class A has a dependency on Class B if it needs an object of Class B in order to do one of its tasks ⦿ Before Class A can use an object of Class B, that object must be instantiated. 36 DI Responsibilities of an IoC Container 1. Declare which dependencies are required for a given object 2. Register classes that are eligible to create these dependent objects 3. Provide a mechanism for creating objects using the info in 1 and 2 37 6 Dependency Injection Walk-through Step 1 1 ApplicationContext will be created and configured by reading configuration meta-data. 39 Step 2 1 2 2 ApplicationContext will create all the beans defined in the configuration meta-data. 40 Step 3 1 Bean A is dependent on Bean B. 3 2 2 All bean dependencies from properties, constructors, factory bean, factory method will get injected at the time of bean creation itself. 41 Step 4 1 Bean A is dependent on Bean B. 3 2b 2a IoC container will Create Bean B (the dependency) before Bean A Before a bean is created and assembled in the IoC container, the IoC container will create any beans on which it depends first. Source: http://www.geekcoders.net/how-dependency-injection-works-in-spring/ 42 DANGER! DANGER! ⦿ Beware of circular dependencies. ⦿ Example: Bean A’s Constructor has an argument that is Bean B, and Bean B’s Constructor has an argument that is Bean A. ⦿ In this case, IoC container will look up “Bean B” while creating “Bean A” and will look up “Bean A” while Creating “Bean B”. It won’t know which to create first. ⦿ Spring will throw the BeanCurrentlyInCreationException. 43 Dependency Injection in Spring 1. Constructor Injection 2. Setter Injection 3. Field Injection Interface injection is not supported by the Spring Framework and Spring’s IoC container. 44 7 Dependency Injection Annotations and Examples Automated Configuration 1. @Component: Registers a class as being managed by Spring (i.e. eligible to be used as a dependency) 2. @Autowired: Instructs Spring that a dependency should be injected 3. @ComponentScan: Instructs Spring where to look for classes annotated with @Component i.e. classes that can be used as dependencies 46 Constructor-based DI @Component public class ClassB { Only … annotated } classes can be used as @Component dependencies public class ClassC { ⦿ The IoC container will … } invoke a constructor with arguments, each @Component public class ClassA { representing a needed ClassB classb; dependency ClassA(ClassB classb){ this.classb = classb; } } Before Spring 4.3, we had to add an @Autowired annotation to the constructor. With newer versions, this is optional if the class has only one constructor. 47 Constructor-based DI @Component ⦿ When you have multiple class ClassA { constructors, explicitly add private ClassB classb; @Autowired to the private ClassC classc; constructor that should be ClassA(ClassB classb) { this.classB = classb; used for DI } @Autowired ClassA(ClassB classb, ClassC classc) { this.classb = classb; this.classc = classC; } } 48 Setter-based DI @Component class ClassA { ⦿ The IoC container will call private ClassB classb; autowired setter methods in the desired class, after @Autowired invoking the no-argument void setClassB(ClassB classb){ this.classb = classb; constructor or no-argument } static factory method to ClassB getClassB() { instantiate the bean return classb; } } 49 Field-based DI @Component ⦿ Spring assigns the required class ClassA { dependencies directly to the @Autowired fields annotated with private ClassB classb; @Autowired annotation. ClassA() { } public ClassB getClassB() { return classc; } 50 Combined @Component class ClassA { ⦿ What types of DI are used in @Autowired this example? private ClassB classB; ⦿ Which injection method will ClassB getClassB() { Spring use for ClassB? return classb; ⦿ Note: it’s considered bad } practice to mix injection @Autowired types on a single class, but void setClassB(ClassB classb) { this.classb = classb; it’s doable. } } 51 Advantages of Constructor DI All required dependencies are available at initialization ⌾ The IoC container makes sure that all the arguments provided in the constructor are available before passing them into the constructor. This helps in preventing the infamous NullPointerException. ⌾ The created object is immutable 52 Advantages of Constructor DI Immutability ⌾ Constructor injection helps in creating immutable objects because a constructor’s signature is the only possible way to create objects. Once we create a bean, we cannot alter its dependencies anymore. 53 Advantages of Constructor DI Identification of Code Smells ⌾ We can easily see if our bean is dependent on too many other objects. ⌾ Could be a sign of infringement on the “separation of responsibilities” principle 54 Advantages of Constructor DI Preventing Errors in Tests ⌾ The constructor forces us to provide valid objects for all dependencies. ⌾ Constructor injection ensures that our test cases are executed only when all the dependencies are available. 55 Advantages of Setter DI Optional Dependencies ⌾ With setter injection, Spring allows us to specify optional dependencies by adding @Autowired(required = false) to a setter method. This is not possible with constructor injection since the required=false would be applied to all constructor arguments. ⌾ We can still provide optional dependencies with constructor injection using Java's Optional type. 56 Disadvantages of Field Injection ⦿ Not recommended by Spring ⦿ Possible only with annotations because Spring implements it using reflection. ⦿ Note: it is used a lot for injection of Mock classes in unit testing. 57 8 Hands-on! Lab 1: Dependency Injection Let’s go through an example of Constructor Injection in Spring Boot. Download the DIActivity_Template Project from Moodle as well as the Dependency Injection Activity Instructions 59 Exercise 1: Constructor Injection ⦿ Implement the Cake class ⦿ Cake class has a dependency on the Flavor class ⦿ Use constructor injection ⦿ Don’t forget to update the DIActivityApplication class! 60 Lab 1 – On Your Own Complete the rest of the lab on your own. Follow the submission instructions and submit on Moodle. 61 7 Homework Homework ⦿ Complete Lab 1 ⦿ Get all your software setup if it isn’t already. 64 8 What’s Next? What’s Next? ⦿ Tiers vs Layers – The 3-tier architecture and the 3- layer pattern 66

Use Quizgecko on...
Browser
Browser