Post

Java自学笔记 (2)

Java自学笔记 (2)

Overview

Primary Components

Spring Core

  • Provides dependency injection
  • Supports aspect-oriented programming

    Spring MVC (Model View Controller)

  • Serves as a web framework
  • Separates
    • Business logic
    • User interface
    • Input processing

      Spring AOP (Aspect Oriented Programming)

  • Manages cross-cutting concerns
    • logging
    • transaction handling
  • Keeps concerns separate from business logic

    Security and data components

    Spring Security

  • Provides a customizable framework
  • Enables authentication and access control
  • Adds security features

    Spring JDBC (Java Database Connectivity)

  • Simplifies database interactions
  • Manages error handling
  • Abstracts JDBC operations

    Web services and batch processing

    Spring Web Flow

  • Simplifies
    • Web app navigation
    • State management

      Spring Web Services

  • Enable SOAP (Simple Object Access Protocol) web services
  • Ensures cross-platform communication

    Spring Batch

  • Supports batch processing
  • Includes
    • Transaction management
    • Chunk processing
    • Job scheduling

      Integration and messaging

  • Spring Integration
    • Helps create message-driven applications
    • Offers extensible framework
  • Spring Data
    • Simplifies CRUD operations
    • Offers a uniform approach to data access

      Key Spring Tools

      Spring Data

      Spring REST Docs

      Spring Boot

      Spring Cloud

      Advanced Features

      Spring WebFlux

  • Handles asynchronous, non-blocking applications
  • Manages high-volume requests efficiently

    Spring for Apache Kafka

  • Builds event-driven system with Kafka
  • Streams messages in real time

    Spring Cloud Gateway

  • A API gateway
  • routes requests and manage security
  • Spring Cloud provides tools for service discovery and circuit breakers, essential for reliable microservices communication.

    Spring Authorization Server

  • Implements OAuth 2.0 and OpenID Connect
  • Secures application with authorization protocols

    Spring AI

  • Uses POJOs (Plain Old Java Objects) as the building blocks for AI applications

    Traditional Development vs. Spring

    Develop Applications

    Comprise

    Applications comprise various components:

    Beans

    Beans are objects managed by Spring Inversion of Control (IoC) container. They are fundamental to a Spring application and form the core components that provide the functionality in a Spring application.

    Services

    Configurations

  • Involves setup and management of Spring components
  • It can be executed through
    • XML files
    • Java annotations:
      • Serves as metadata
      • They provide key information about how Beans should be managed
      • Acts like a product label
      • Provides important details about its contents, without needing separate documentation
    • Java-based classes
  • The configuration is like a building’s blueprint, which outlines how each room or bean should be constructed and maintained within the structure. ```java @Component public class CatService { public void meow() { System.out.println(“Meow!”); } }

@Service public class CatController { private final CatService catService;

1
2
3
4
5
6
7
8
@Autowired
public CatController(CatServcie catService) {
	this.catService = catService;
}

public void speak() {
	catService.meow();  //使用注入的Bean,不需要用new来实例化
} } ``` ==这里面的`@Component`, `@Service`, `@Autowired` 都是annotations。给`CatService` 这个class加上`@Component`的注解,Spring在启动时就会自动扫描,然后把它变成一个Bean,放进它的容器(ApplicationContext)里。`@Autowired`这个注解相当于是个声明,只要加上这个注解就不需要写很多个new来实例化或者初始化一些参数或者方法,Spring会帮忙塞进来,也就是“注入 (injection)”== ## Work Together These components work together to:  - Perform tasks - Handle requests - Manage data - Implement business logic ## Application Context Manages beans and their dependencies throughout the application's lifecycle. It provides instructions for creating and managing the various Beans that make up the application. It ensures that all necessary components are available when required. ## Dependencies Dependencies are **objects** required by other objects. They enable objects to work together effectively within an application. ### Dependency Injection (DI) A technique that allows dependencies to be injected into objects at runtime. Spring automatically provides dependencies instead of allowing an object to create them. ### Autowiring Autowiring is a Spring feature that automatically injects the necessary dependencies into Beans without explicitly defining them in the configuration. Spring uses **reflection** to match the correct beans based on their type or name. ## Inversion of Control (IoC) IoC is a key principle that transfer the responsibility of creating and managing dependencies from the application code to the Spring framework. Rather than manually creating objects, such as an engine for a car, Spring provides the necessary components during bean initialization.

IntelliJ

IntelliJ is an IDE developed by JetBrains.

Annotations

Annotations in the Spring framework are categorized based on their purpose and placement within the code

Class-level annotations

  • Placed ==above== the class declaration to define it as a Spring-managed bean.
  • They help Spring:
    • identify and register the class
    • enable dependency injection and framework functionalities

      @Component

  • Declares a class as a bean
  • Allows automatic registration in IoC container ```java import org.springframework.stereotype.Component;

@Component public class BookService { public void listBooks() { System.out.println(“Listing all books”); } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
### @Service
### @Repository
### @Controller
- Marks a class as a web controller
- Allows handling of HTTP requests
```java
import org.springframework.stereotype.Component;
import rg.springframework.web.bind.annotation.GetMapping;

@Controller
public class BookController {
	@GetMapping("/books")
	public String showBooks() {
		return "books";  //returns the view name "books"
	}
}

这个例子里,@Controller 这个注释让 BookController 这个class可以处理请求,并且返回名为”books”的视图。 @GetMapping("/books") 的意思是浏览器或客户端发送一个GET请求到”/books”这个路径,而加上@之后的这个annotation会让Spring调用对应的方法,在这个例子里,被调用的方法就是showBooks(),然后这个方法返回了一个视图名称,Spring就会根据这个名字去招对应的模板文件,比如books.html。如果项目中按照模板结构找到了这个books.html,那么这个页面就会被渲染出来。

Method-level annotations

  • Placed above method declarations to configure the behavior
  • They tell Spring how the method should be executed, such as:
    • defining routes in a web application
    • managing transactions

      @Bean

  • An annotation used inside a @Configuration class to define a method that returns an object managed by the Spring container

    @RequestMapping

  • Maps HTTP requests to specific methods or classes in an MVC application ```java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;

@Controller public class BookController { @RequestMapping(“/books”) public String getBooks() { return “books”; } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
### @GetMapping
## Field-level annotations
- Placed directly above fields to inject dependencies or values
- They allow Spring to automatically provide:
	- required object
	- external property values
- Avoid manual instantiation
### @Autowired
- Enable automatic dependency injection
- Allows the Spring container to resolve and inject dependencies without explicit configuration
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BookController {
	@Autowired
	private BookService bookService;
	public void displayBooks() {
		bookService.listBooks();
	}
}

@Value

  • Injects values from:
    • property files
    • system environment variables
    • default values into Spring-managed Beans
      1
      2
      3
      4
      5
      6
      7
      8
      
      @Component
      public class Library {
        @Valu("${library.name}")
        private String libraryName;
        public void printLibraryName() {
        System.out.println("Library Name: " + libraryName);
        }
      }
      

      In this example, @Value assigns a property value to the LibraryName filed

      @Qualifier

      Constructor and parameter - level annotations

  • Examples
    • @Autowired
    • Qualifier
  • Placed on constructors and parameters
  • Ensure the correct dependencies are injected
  • This is useful for enforcing dependency injections in classes with multiple dependencies
    1
    2
    3
    4
    5
    6
    7
    
    public class Library {
      private final BookService bookService;
      @Autowired
      public Library(@Qualifier("specificBookService") BookService bookService) {
          this.bookService = bookService;
      }
    }
    

    Other annotations

    @Configuration

  • Marks a class as a source of Bean definitions for the application context
  • Allows Spring to manage and instantiate beans ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;

@Configuration public class AppConfig { @Bean public BookService bookService() { return new BookService(); } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
`AppConfig` defines a `BookService` Bean created and managed by Spring.
### @PathVariable
- Extracts values from the URI (Uniform Resource Identifier) path
- Binds the values to method parameters
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class BookController {
	@GetMapping("/books/{id}")
	public String getBookById(@PathVariable("id") String bookId) {
		System.out.println("Book ID: " + bookId);
		return "bookDetails";
	}
}

@RestController

  • Combines @Controller and @ResponseBody
  • Makes it suitable for building RESTful web services ```java import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping;

@RestController public class BookRestController { @GetMapping(“/api/books”) public List getAllBooks() { return Array.asList("Spring Boot", "Spring Cloud"); } }

1
2
3
4
5
6
7
8
9
10
11
In this example, `BookRestController` returns JSON response for API requests.
### @RequestParam
- Extracts query parameters from an HTTP request and binds them to method parameters
```java
@RestController
public clss BookRestController {
	@GetMapping("/api/book")
	public String getBodyByTitle(@RequestParam("title") String title) {
		return "Book title: " + title;
	}
}

@ResponseBody

在上面那个book tilte的例子里,@ResponseBody tells Spring to write the method’s return value directly to the HTTP response body instead of resolving it as a view

@Scope

  • Defines bean lifecycle and visibility
    1
    2
    3
    4
    5
    
    @Component
    @Scope("prototype")
    public class Book {
      // Bean definition for a prototype scope
    }
    

    In this example, @Scope ensures that a new instance of Book is created each time requested

Maven

Maven is a powerful project management and comprehension tool used mainly for Java projects.  It provides a framework to automate the software build process, helping developers manage dependencies, compile code, run tests, and package applications.

Key aspects

POM (Project Object Model) file

  • pom.xml
  • Contains project information:
    • Configuration details
    • Project building process
    • Project dependencies
    • Various build processes ```xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
### Dependencies
- Declared in pom.xml, and automatically downloaded from the central repository
### Repositories
### Build life cycle
- Consists of the **validate, compile, test, package, verify, install, and deploy** phases
### Plug-ins

# Spring Boot
## Key features
- **Auto-configuration**: Set up components automatically
- **Standalone applications**: With standalone applications, Spring Boot **embeds a web server**, (e.g., Tomcat, Jetty, or Undertow) allowing applications to run independently without setting up an external server. (这是和传统的Java开发对应的优势。传统的Java开发需要自己安装外部服务器,打包应用,然后自己部署,才可以启动服务器来运行应用。)
- **Production-ready features**: Include monitoring and management tools
- **Spring Boot Command Line Interface (CLI)**: Supports quick prototyping with **Groovy** scripts
- **Spring Initializr**: Generates structured projects with dependencies
## Concepts
### Auto-configuration
- Sets up beans and components automatically.
- Example: Configures database connections, such as H2 or MySQL, based on dependencies automatically
### Embedded server
Spring Boot includes a built-in web server, such as Tomcat or Jetty, allowing applications to run independently.
### Actuator
Includes **endpoints to monitor key metrics and system status**, providing insights into an application's health and performance.
### Externalized configuration
Separates **settings** from the codebase using **properties, or YAML files**, helps to manage applications across different environments.
## Spring Boot Structure

my-spring-boot-app/ | |__ pom.xml |__ src/ |__ main/ |__ java/ | |__ com/ | | |__ example/ | | |__ demo/ | | |__ DemoApplication.java | | |__ controller/ | | |__ service/ | | |__ repository/ | | |__ model/ | |__ resources/ | |__ application.properties | |__ static/ | |__ templates/ |__ test/ |__ java/ |__ com/ |__ example/ |__ demo/ ```

  • pom.xml: manages dependencies and build configurations
  • src/: contains Java source files organized into structured packages
    • demo/:
      • DemoApplication.java: ==main application class== - is annotated with @SpringBootApplication, is the ==entry point==.
      • controller/: handles HTTP requests (@Controller, @RestController)
      • service/: contains business logic (@Service)
      • repository/: manages data access (@Repository)
      • model/: includes entity classes representing domain objects (@Entity)
    • resources/: stores configuration files and static assets
      • application.properties: is the configuration file. It manages the settings (database connections, server ports).
      • static/: includes CSS, JavaScript, and images
      • templates/: store view templates for rendering web pages using Timeleaf or FreeMarker
    • test/: ensures application reliability through structured testing
      • java/: contains test classes, mirroring the main source structure, allowing each component to have corresponding tests

Key Spring Boot annotations

App Servers

MVC

Model

Contains data and business logic

View

What is displayed for the user in the browser

Controller

  • Receives requests from users
  • Processes user requests using the Model
  • Selects the appropriate view to display the results

    Security

    Security mechanisms

  • Authentication:
    • Verifies identity: typically through a username and password
  • Authorization:
    • Determines actions (what you do)
    • Roles
    • Authorities: Specify actions a role can perform, including permission
    • Method-level security:
      • Controls access to specific methods within the application
      • Uses annotations to add an extra layer of security beyond URL-based access control
  • HTTP basic authentication
  • Form-based authentication
  • Password storage and encoding
  • CSRF protection:
    • Prevents attackers from tricking authenticated users
    • Blocks unintended actions on different websites
  • Role-based access control (RBAC):
    • Assign access based on roles
    • Organize permissions by grouping them under specific roles and determining who can perform certain actions
  • Integration with other authentication systems
This post is licensed under CC BY 4.0 by the author.

Comments 0

Loading comments...
Leave a Comment
Your Mastodon, Pleroma, or other Fediverse account handle
0 / 5000 characters