Java 学习路线:语言、框架、中间件与数据库

Java 是一门功能强大、应用广泛的编程语言,适用于企业级应用、Web 开发、大数据处理、Android 开发等各种场景。这里为大家介绍了一下我认为较为合适的学习路线

一、Java基础

1.1 Java语言基础

1.1.1 安装JDK和IDE
  • 安装JDK

    • 下载 JDK:访问 Oracle 官网,下载最新的 Java Development Kit(JDK)。

    • 安装 JDK:按照操作系统要求安装 JDK 并配置环境变量。

    • Windows上配置环境变量:

      1. 打开 "系统属性" -> "高级系统设置" -> "环境变量"。
      2. 新建JAVA_HOME,指向 JDK 安装路径,如C:\Program Files\Java\jdk-14
      3. Path中增加%JAVA_HOME%\bin
  • 选择开发工具(IDE)

1.1.2 基本语法(网络摘抄,简单说明)
  • Hello World 程序

     

    java

    public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
  • 注释:Java 支持单行注释 (//)、多行注释 (/* ... */) 和文档注释 (/** ... */)。

1.1.3 数据类型和变量
  • 基本数据类型:int、float、double、char、boolean 等。
  • 变量声明和初始化
     

    java

    int number = 10; double price = 99.99; char grade = 'A'; boolean isTrue = true;
1.1.4 运算符和表达式
  • 算术运算符+-*/%
  • 关系运算符==!=><>=<=
  • 逻辑运算符&&||!
1.1.5 控制结构
  • 条件语句ifelse ifelseswitch
  • 循环语句forwhiledo-while
1.1.6 数组
  • 声明和初始化数组
     

    java

    int[] numbers = {1, 2, 3, 4, 5}; String[] names = new String[3];

1.2 面向对象编程

1.2.1 类与对象
  • 定义类

     

    java

    public class Car { String color; String model; void drive() { System.out.println("Car is driving"); } }
  • 创建对象

     

    java

    Car myCar = new Car(); myCar.color = "Red"; myCar.model = "Toyota"; myCar.drive();
1.2.2 继承和多态
  • 继承

     

    java

    public class Animal { void makeSound() { System.out.println("Animal sound"); } } public class Dog extends Animal { @Override void makeSound() { System.out.println("Bark"); } } Dog dog = new Dog(); dog.makeSound(); // 输出:Bark
  • 多态

     

    java

    Animal animal = new Dog(); animal.makeSound(); // 输出:Bark
1.2.3 封装与接口
  • 封装

     

    java

    public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
  • 接口

     

    java

    interface Animal { void eat(); void sleep(); } class Cat implements Animal { public void eat() { System.out.println("Cat eats"); } public void sleep() { System.out.println("Cat sleeps"); } }

1.3 常用类库

1.3.1 字符串处理
  • 字符串操作
     

    java

    String str = "Hello, World!"; int length = str.length(); String upperCaseStr = str.toUpperCase();
1.3.2 集合框架
  • List 接口

     

    java

    List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob");
  • Set 接口

     

    java

    Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(2);
  • Map 接口

     

    java

    Map<String, Integer> map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30);
1.3.3 输入与输出(I/O)
  • 文件操作
     

    java

    try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }

1.4 异常处理

  • 基本用法
     

    java

    try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("This block is always executed"); }

二、高级 Java 编程

2.1 多线程与并发

2.1.1 线程基础
  • 创建线程

     

    java

    class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } MyThread thread = new MyThread(); thread.start();
  • 实现 Runnable 接口

     

    java

    class MyRunnable implements Runnable { public void run() { System.out.println("Runnable is running"); } } Thread thread = new Thread(new MyRunnable()); thread.start();
2.1.2 并发工具
  • 线程池

     

    java

    ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { executor.submit(() -> { System.out.println("Task is running"); }); } executor.shutdown();
  • 并发集合

     

    java

    ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Alice", 25); map.put("Bob", 30);

2.2 网络编程

  • Socket 编程
     

    java

    try (ServerSocket serverSocket = new ServerSocket(8080)) { Socket socket = serverSocket.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = reader.readLine(); System.out.println("Received: " + line); } catch (IOException e) { e.printStackTrace(); }

2.3 Java 反射

  • 基本用法
     

    java

    Class<?> clazz = Class.forName("com.example.MyClass"); Method method = clazz.getMethod("myMethod"); Object instance = clazz.newInstance(); method.invoke(instance);

2.4 Lambda 表达式与 Stream API

  • Lambda 表达式

     

    java

    List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(name -> System.out.println(name));
  • Stream API

     

    java

    List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println);

三、Java Web 开发

3.1 Servlet 与 JSP

3.1.1 Servlet 基础
  • 创建 Servlet
     

    java

    @WebServlet("/hello") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello, Servlet!"); } }
3.1.2 JSP 基础
  • 创建 JSP 页面
     

    jsp

    <html> <body> <h1>Hello, JSP!</h1> </body> </html>

3.2 使用 Spring 框架

3.2.1 Spring 核心容器
  • 配置 Spring
     

    xml

    <!-- applicationContext.xml --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="myBean" class="com.example.MyBean"> <property name="property" value="value"/> </bean> </beans>
3.2.2 Spring MVC
  • 配置 Spring MVC

     

    xml

    <!-- dispatcher-servlet.xml --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启用 Spring MVC 注解驱动 --> <mvc:annotation-driven/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 启用组件扫描 --> <context:component-scan base-package="com.example"/> </beans>
  • 创建控制器

     

    java

    @Controller public class HomeController { @RequestMapping("/home") public String home(Model model) { model.addAttribute("message", "Hello, Spring MVC!"); return "home"; } }

3.3 使用 MyBatis

3.3.1 配置 MyBatis
  • 配置 MyBatis
     
    <!-- mybatis-config.xml -->
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/yourdbname"/>
                    <property name="username" value="root"/>
                    <property name="password" value="password"/>
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <mapper resource="com/example/mapper/YourMapper.xml"/>
        </mappers>
    </configuration>
    
3.3.2 配置 MyBatis Spring
  • Spring 配置

     
    <!-- applicationContext.xml -->
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/yourdbname"/>
            <property name="username" value="root"/>
            <property name="password" value="password"/>
        </bean>
    
        <!-- 配置 SqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
        <!-- 配置 MapperScannerConfigurer -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.example.mapper"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    
    </beans>
    
  • 编写 Mapper 接口

     

    java

    @Mapper public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(int id); }

四、进阶技术与框架

4.1 Spring Boot

4.1.1 Spring Boot 简介

Spring Boot 是 Spring 框架的子项目,可简化 Spring 应用的开发与配置。通过提供一系列默认配置和自动化配置功能,Spring Boot 极大地减轻了开发者的工作量。

4.1.2 创建 Spring Boot 项目
  • 使用 Spring Initializr: 访问 Spring Initializr,选择适当的配置生成一个 Spring Boot 项目。

  • 基本配置: 在 application.properties 文件中进行一些基本的配置。

     

    properties

    server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/yourdbname spring.datasource.username=root spring.datasource.password=password
4.1.3 编写 Spring Boot 应用
  • 主应用类

     

    java

    @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
  • 简单的控制器

     

    java

    @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Spring Boot!"; } }

4.2 Spring Cloud

4.2.1 Spring Cloud 简介

Spring Cloud 是一系列框架的集合,用于开发分布式系统和微服务架构。它涵盖了负载均衡、服务发现、配置管理、分布式追踪等功能。

4.2.2 常用组件
  • Eureka:服务发现与注册。
  • Ribbon:客户端负载均衡。
  • Feign:声明式 HTTP 客户端。
  • Config:分布式配置管理。
4.2.3 简单示例
  • 创建 Eureka 服务器

     

    java

    @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }

    application.properties 中配置 Eureka:

     

    properties

    eureka.client.register-with-eureka=false eureka.client.fetch-registry=false server.port=8761
  • 创建服务提供者

     

    java

    @SpringBootApplication @EnableEurekaClient public class ServiceProviderApplication { public static void main(String[] args) { SpringApplication.run(ServiceProviderApplication.class, args); } }

    application.properties 中配置 Eureka 客户端:

     

    properties

    eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

    简单的控制器:

     

    java

    @RestController public class ServiceProviderController { @GetMapping("/greet") public String greet() { return "Hello from Service Provider"; } }

4.3 MyBatis Plus

4.3.1 MyBatis Plus 简介

MyBatis-Plus 是 MyBatis 的增强工具,它在 MyBatis 的基础上提供了大量的易用功能,如单表 CRUD 操作、分页、代码生成器等,旨在简化数据库操作。

4.3.2 使用 MyBatis Plus
  • 添加依赖: 在 pom.xml 文件中添加 MyBatis-Plus 依赖。

     

    xml

    <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.4</version> </dependency>
  • 配置 MyBatis Plus

     

    java

    @Configuration @MapperScan("com.example.mapper") public class MyBatisPlusConfig { }
  • 编写 Mapper 接口

     

    java

    public interface UserMapper extends BaseMapper<User> { }

4.4 前后端分离框架

4.4.1 使用 Spring Boot 和前端框架(Vue/React)
  • 基本架构

    • 后端使用 Spring Boot 提供 RESTful API 服务,前端使用 Vue.js 或 React.js 构建用户界面。
  • 后端实现

    • 使用 Spring Boot 创建 RESTful API。
    • 数据返回 JSON 格式,前后端通过 HTTP 请求进行交互。
  • 前端实现

    • 使用 Vue CLI 或 Create React App 快速搭建前端项目。
    • 通过 Ajax 调用后端 API,例如使用 Axios 进行 HTTP 请求。
4.4.2 简单示例
  1. 建立 Spring Boot 项目

    • 通过 Spring Initializr 创建一个包含 Web 依赖的 Spring Boot 项目。
  2. 编写 RESTful 控制器

     

    java

    @RestController @RequestMapping("/api") public class UserController { @Autowired private UserService userService; @GetMapping("/users") public List<User> getAllUsers() { return userService.getAllUsers(); } }
  3. 建立前端项目(以 Vue.js 为例)

     

    bash

    vue create my-frontend cd my-frontend npm install axios
  4. 编写前端代码

     

    javascript

    <template> <div> <h1>User List</h1> <ul> <li v-for="user in users" :key="user.id">{{ user.name }}</li> </ul> </div> </template> <script> import axios from 'axios'; export default { data() { return { users: [] }; }, mounted() { axios.get('/api/users') .then(response => { this.users = response.data; }) .catch(error => { console.log(error); }); } }; </script>

4.5 Spring Security

4.5.1 Spring Security 简介

Spring Security 是一个强大的安全框架,提供了全面的身份验证、授权与保护功能。它可以保护 Spring 应用免受常见的安全威胁。

4.5.2 使用 Spring Security
  • 添加依赖: 在 pom.xml 中添加 Spring Security 依赖。

     

    xml

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
  • 编写配置类

     
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/public/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
        }
    }
    
  • 创建登录页面

     

    html

    <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form th:action="@{/login}" method="post"> <div> <label>Username: <input type="text" name="username"/></label> </div> <div> <label>Password: <input type="password" name="password"/></label> </div> <div> <input type="submit" value="Log in"/> </div> </form> </body> </html>

五、知名中间件使用

5.1 RabbitMQ

5.1.1 RabbitMQ 简介

RabbitMQ 是一个消息队列中间件,广泛用于实现异步通信、消息传递、分布式系统中解耦和流量削峰。

5.1.2 安装和配置 RabbitMQ
  • 安装 RabbitMQ(以 Ubuntu 为例):
     

    bash

    sudo apt-get update sudo apt-get install rabbitmq-server sudo systemctl enable rabbitmq-server sudo systemctl start rabbitmq-server
5.1.3 编写生产者和消费者
  • 生产者代码

     
    import com.rabbitmq.client.ConnectionFactory;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.Channel;
    
    public class Producer {
        private final static String QUEUE_NAME = "hello";
    
        public static void main(String[] argv) throws Exception {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            try (Connection connection = factory.newConnection();
                 Channel channel = connection.createChannel()) {
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                String message = "Hello, RabbitMQ!";
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
            }
        }
    }
    
  • 消费者代码

     
    import com.rabbitmq.client.ConnectionFactory;
    import com.rabbitmq.client.Connection;
    import com.rabbitmq.client.Channel;
    import com.rabbitmq.client.DeliverCallback;
    
    public class Consumer {
        private final static String QUEUE_NAME = "hello";
    
        public static void main(String[] argv) throws Exception {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            try (Connection connection = factory.newConnection();
                 Channel channel = connection.createChannel()) {
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    
                DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                    String message = new String(delivery.getBody(), "UTF-8");
                    System.out.println(" [x] Received '" + message + "'");
                };
                channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
            }
        }
    }
    

5.2 Apache Kafka

5.2.1 Kafka 简介

Apache Kafka 是一个分布式流处理平台,能够高效地发布和订阅消息,同时通过高容错性和高吞吐量支持大规模消息处理。

5.2.2 安装和配置 Kafka
  • 安装 Kafka: 访问 Kafka 官网下载并解压 Kafka。

  • 启动 Zookeeper 和 Kafka

     

    bash

    bin/zookeeper-server-start.sh config/zookeeper.properties bin/kafka-server-start.sh config/server.properties
5.2.3 编写生产者和消费者
  • 生产者代码

     
    import org.apache.kafka.clients.producer.*;
    
    import java.util.Properties;
    
    public class KafkaProducerExample {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("bootstrap.servers", "localhost:9092");
            props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
            props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    
            Producer<String, String> producer = new KafkaProducer<>(props);
    
            for (int i = 0; i < 10; i++) {
                String key = Integer.toString(i);
                String value = "Hello Kafka " + i;
                ProducerRecord<String, String> record = new ProducerRecord<>("my-topic", key, value);
                producer.send(record);
            }
    
            producer.close();
        }
    }
    
  • 消费者代码

     
    import org.apache.kafka.clients.consumer.*;
    
    import java.util.Collections;
    import java.util.Properties;
    
    public class KafkaConsumerExample {
        public static void main(String[] args) {
            Properties props = new Properties();
            props.put("bootstrap.servers", "localhost:9092");
            props.put("group.id", "test-group");
            props.put("enable.auto.commit", "true");
            props.put("auto.commit.interval.ms", "1000");
            props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
            props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
    
            KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
            consumer.subscribe(Collections.singletonList("my-topic"));
    
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(100);
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
                }
            }
        }
    }
    

5.3 Redis

5.3.1 Redis 简介

Redis 是一个开源的内存中数据结构存储系统,支持多种数据结构,如字符串、哈希、列表、集合、有序集合、位图和地理空间索引等。它常被用作数据库、缓存和消息中间件。

5.3.2 安装和配置 Redis
  • 安装 Redis(以 Ubuntu 为例):
     

    bash

    sudo apt-get update sudo apt-get install redis-server sudo systemctl enable redis-server sudo systemctl start redis-server
5.3.3 使用 Jedis 操作 Redis
  • 添加 Jedis 依赖: 在 pom.xml 中添加 Jedis 依赖。

     

    xml

    <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.5.0</version> </dependency>
  • 基本操作示例

     
    import redis.clients.jedis.Jedis;
    
    public class RedisExample {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("localhost");
    
            // 设置和获取数据
            jedis.set("key", "value");
            String value = jedis.get("key");
            System.out.println("Stored value: " + value);
    
            // 列表操作
            jedis.lpush("list", "element1", "element2");
            System.out.println("Stored list elements: " + jedis.lrange("list", 0, -1));
    
            // 哈希操作
            jedis.hset("hash", "field1", "value1");
            System.out.println("Stored hash fields: " + jedis.hgetAll("hash"));
    
            // 集合操作
            jedis.sadd("set", "element1", "element2");
            System.out.println("Stored set elements: " + jedis.smembers("set"));
    
            jedis.close();
        }
    }
    
    jedis.close(); } }

5.4 Elasticsearch

5.4.1 Elasticsearch 简介

Elasticsearch 是一个分布式的搜索和分析引擎,可以实时地存储、搜索和分析海量数据。它建立在 Apache Lucene 之上,提供了 RESTful API 和分布式特性。

5.4.2 安装和配置 Elasticsearch
  • 安装 Elasticsearch(以 Ubuntu 为例):
     

    bash

    wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add - sudo apt-get update echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list sudo apt-get update sudo apt-get install elasticsearch sudo systemctl enable elasticsearch sudo systemctl start elasticsearch
5.4.3 使用 Spring Data Elasticsearch
  • 添加依赖: 在 pom.xml 中添加 Spring Data Elasticsearch 依赖。

     

    xml

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
  • 配置 Elasticsearch: 在 application.properties 配置文件中添加 Elasticsearch 配置。

     

    properties

    spring.elasticsearch.rest.uris=http://localhost:9200
  • 定义索引实体

     

    java

    import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "products") public class Product { @Id private String id; private String name; private double price; // Getters and setters }
  • 定义存储库接口

     

    java

    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface ProductRepository extends ElasticsearchRepository<Product, String> { }
  • 使用 Elasticsearch

     

    java

    @Service public class ProductService { @Autowired private ProductRepository productRepository; public void saveProduct(Product product) { productRepository.save(product); } public Iterable<Product> findAllProducts() { return productRepository.findAll(); } }
  • 控制器示例

     

    java

    @RestController @RequestMapping("/api/products") public class ProductController { @Autowired private ProductService productService; @PostMapping public void addProduct(@RequestBody Product product) { productService.saveProduct(product); } @GetMapping public Iterable<Product> getAllProducts() { return productService.findAllProducts(); } }

六、数据库技术

6.1 MySQL

6.1.1 MySQL 简介

MySQL 是全球最流行的开源关系型数据库管理系统,其广泛应用于 Web 应用开发中,具有高性能、可靠性和易用性。

6.1.2 安装和配置 MySQL
  • 安装 MySQL(以 Ubuntu 为例):

     

    bash

    sudo apt-get update sudo apt-get install mysql-server sudo systemctl start mysql sudo systemctl enable mysql
  • 基本配置

     sudo mysql_secure_installation 
6.1.3 使用 JDBC 访问 MySQL
  • 添加 JDBC 依赖: 在 pom.xml 中添加 MySQL 连接器依赖。

     

    xml

    <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency>
  • JDBC 示例

     
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class JDBCExample {
        public static void main(String[] args) {
            String jdbcUrl = "jdbc:mysql://localhost:3306/yourdbname";
            String username = "root";
            String password = "password";
    
            try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
                 Statement statement = connection.createStatement()) {
    
                String createTableSql = "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT, name VARCHAR(255), PRIMARY KEY (id))";
                statement.executeUpdate(createTableSql);
    
                String insertSql = "INSERT INTO users (name) VALUES ('Alice')";
                statement.executeUpdate(insertSql);
    
                String selectSql = "SELECT id, name FROM users";
                ResultSet resultSet = statement.executeQuery(selectSql);
    
                while (resultSet.next()) {
                    System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name"));
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

6.2 PostgreSQL

6.2.1 PostgreSQL 简介

PostgreSQL 是一个功能强大、开放源代码的对象-关系型数据库系统,以其高可扩展性、强一致性以及对复杂查询的支持而广受欢迎。

6.2.2 安装和配置 PostgreSQL
  • 安装 PostgreSQL(以 Ubuntu 为例):
     

    bash

    sudo apt-get update sudo apt-get install postgresql postgresql-contrib sudo systemctl start postgresql sudo systemctl enable postgresql
6.2.3 使用 JDBC 访问 PostgreSQL
  • 添加 JDBC 依赖: 在 pom.xml 中添加 PostgreSQL 连接器依赖。

     

    xml

    <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.18</version> </dependency>
  • JDBC 示例

     
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    public class PostgreSQLJDBCExample {
        public static void main(String[] args) {
            String jdbcUrl = "jdbc:postgresql://localhost:5432/yourdbname";
            String username = "postgres";
            String password = "password";
    
            try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
                 Statement statement = connection.createStatement()) {
    
                String createTableSql = "CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(255))";
                statement.executeUpdate(createTableSql);
    
                String insertSql = "INSERT INTO users (name) VALUES ('Alice')";
                statement.executeUpdate(insertSql);
    
                String selectSql = "SELECT id, name FROM users";
                ResultSet resultSet = statement.executeQuery(selectSql);
    
                while (resultSet.next()) {
                    System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + resultSet.getString("name"));
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

6.3 MongoDB

6.3.1 MongoDB 简介

MongoDB 是一个面向文档的 NoSQL 数据库,以 JSON-like 的 BSON 格式存储数据,具有高性能、易扩展和灵活的数据结构。

  • 安装 MongoDB(以 Ubuntu 为例):

     

    bash

    sudo apt-get update sudo apt-get install -y mongodb sudo systemctl start mongodb sudo systemctl enable mongodb
  • 使用 mongo shell 验证安装

     

    bash

    mongo
6.3.3 使用 Java 客户端操作 MongoDB
  • 添加 MongoDB Java 驱动依赖: 在 pom.xml 中添加 MongoDB Java 驱动依赖。

     

    xml

    <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.3.3</version> </dependency>
  • Java 示例代码

     
    import com.mongodb.client.MongoClients;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    import org.bson.Document;
    
    public class MongoDBExample {
        public static void main(String[] args) {
            try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {
                MongoDatabase database = mongoClient.getDatabase("testdb");
    
                MongoCollection<Document> collection = database.getCollection("users");
    
                // 插入文档
                Document document = new Document("name", "Alice")
                        .append("age", 25);
                collection.insertOne(document);
    
                // 查询文档
                for (Document doc : collection.find()) {
                    System.out.println(doc.toJson());
                }
            }
        }
    }
    

6.4 Neo4j

6.4.1 Neo4j 简介

Neo4j 是一个高性能的、NOSQL 图形数据库,使用图数据模型储存数据。它非常适合用于复杂关系查询,例如社交网络、推荐系统等。

6.4.2 安装和配置 Neo4j
  • 安装 Neo4j(以 Ubuntu 为例):

     

    bash

    wget -O - https://debian.neo4j.com/neotechnology.gpg.key | sudo apt-key add - echo 'deb https://debian.neo4j.com stable 4.0' | sudo tee /etc/apt/sources.list.d/neo4j.list sudo apt-get update sudo apt-get install -y neo4j sudo systemctl start neo4j sudo systemctl enable neo4j
  • 使用 Neo4j Browser 验证安装: 打开浏览器,访问 http://localhost:7474/

6.4.3 使用 Java 客户端操作 Neo4j
  • 添加 Neo4j Java 驱动依赖: 在 pom.xml 中添加 Neo4j Java 驱动依赖。

     

    xml

    <dependency> <groupId>org.neo4j.driver</groupId> <artifactId>neo4j-java-driver</artifactId> <version>4.2.5</version> </dependency>
  • Java 示例代码

    import org.neo4j.driver.AuthTokens;
    import org.neo4j.driver.Driver;
    import org.neo4j.driver.GraphDatabase;
    import org.neo4j.driver.Session;
    
    public class Neo4jExample {
        public static void main(String[] args) {
            Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "password"));
    
            try (Session session = driver.session()) {
                // 创建节点
                session.run("CREATE (n:Person {name: 'Alice', age: 25})");
    
                // 查询节点
                var result = session.run("MATCH (n:Person{name:'Alice'}) RETURN n.name AS name, n.age AS age");
                while (result.hasNext()) {
                    var record = result.next();
                    System.out.println(record.get("name").asString() + " - " + record.get("age").asInt());
                }
            }
    
            driver.close();
        }
    }
    

七、项目实战与最佳实践

网络上的项目往往非常常见,建议去一些代码平台学习进一步的进行学习

7.1 项目实战

  • 在线商城系统:一个典型的在线商城系统,包括用户注册登录、商品展示、购物车、订单管理等模块。

  • 博客系统:实现用户可以发表文章、评论、分类、标签等功能。

7.2 最佳实践

  • 版本控制:使用 Git 进行版本控制,使用 GitHub 或 GitLab 进行协作管理。

  • 编程规范和代码风格:遵循 Java 编码规范,提高代码的可读性和可维护性。

  • 单元测试和集成测试:编写单元测试和集成测试,确保代码质量。

  • 持续集成:使用 Jenkins 等持续集成工具,实现自动化构建和测试。

  • 性能优化:使用缓存、数据库优化、内存管理等技术进行性能优化。

八、总结

通过这篇详细的 Java 学习路线,你可以系统性地掌握 Java 基础、高级编程技术、热门框架、知名中间件和数据库技术。以下是学习路线的总结:

  1. Java 基础:学习 Java 基本语法、面向对象编程、常用类库和异常处理。
  2. 高级 Java 编程:掌握多线程与并发、网络编程、反射、Lambda 表达式与 Stream API。
  3. Java Web 开发:学习 Servlet 与 JSP、Spring 框架、MyBatis,并结合 Spring Boot 和前端框架实现前后端分离开发。
  4. 知名中间件使用:掌握 RabbitMQ、Kafka、Redis 和 Elasticsearch 等中间件的安装、配置及使用。
  5. 数据库技术:学习 MySQL、PostgreSQL、MongoDB 和 Neo4j 数据库的安装、配置及使用。
  6. 项目实战与最佳实践:通过实际项目实践,掌握版本控制、编程规范、测试和性能优化的最佳实践。

希望这篇文章能对你学习 Java 有所帮助,如果你有任何问题或建议,欢迎留言讨论。

  • 21
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值