Java 是一门功能强大、应用广泛的编程语言,适用于企业级应用、Web 开发、大数据处理、Android 开发等各种场景。这里为大家介绍了一下我认为较为合适的学习路线
安装JDK:
下载 JDK:访问 Oracle 官网,下载最新的 Java Development Kit(JDK)。
安装 JDK:按照操作系统要求安装 JDK 并配置环境变量。
Windows上配置环境变量:
JAVA_HOME
,指向 JDK 安装路径,如C:\Program Files\Java\jdk-14
。Path
中增加%JAVA_HOME%\bin
。选择开发工具(IDE):
Hello World 程序:
java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
注释:Java 支持单行注释 (//
)、多行注释 (/* ... */
) 和文档注释 (/** ... */
)。
java
int number = 10; double price = 99.99; char grade = 'A'; boolean isTrue = true;
+
, -
, *
, /
, %
==
, !=
, >
, <
, >=
, <=
&&
, ||
, !
if
, else if
, else
, switch
for
, while
, do-while
java
int[] numbers = {1, 2, 3, 4, 5}; String[] names = new String[3];
定义类:
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();
继承:
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
封装:
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"); } }
java
String str = "Hello, World!"; int length = str.length(); String upperCaseStr = str.toUpperCase();
List 接口:
java
List names = new ArrayList<>(); names.add("Alice"); names.add("Bob");
Set 接口:
java
Set numbers = new HashSet<>(); numbers.add(1); numbers.add(2);
Map 接口:
java
Map map = new HashMap<>(); map.put("Alice", 25); map.put("Bob", 30);
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(); }
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
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();
线程池:
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 map = new ConcurrentHashMap<>(); map.put("Alice", 25); map.put("Bob", 30);
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(); }
java
Class> clazz = Class.forName("com.example.MyClass"); Method method = clazz.getMethod("myMethod"); Object instance = clazz.newInstance(); method.invoke(instance);
Lambda 表达式:
java
List names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(name -> System.out.println(name));
Stream API:
java
List names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println);
java
@WebServlet("/hello") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello, Servlet!"); } }
jsp
Hello, JSP!
xml
配置 Spring MVC:
xml
创建控制器:
java
@Controller public class HomeController { @RequestMapping("/home") public String home(Model model) { model.addAttribute("message", "Hello, Spring MVC!"); return "home"; } }
Spring 配置:
编写 Mapper 接口:
java
@Mapper public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User getUserById(int id); }
Spring Boot 是 Spring 框架的子项目,可简化 Spring 应用的开发与配置。通过提供一系列默认配置和自动化配置功能,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
主应用类:
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!"; } }
Spring Cloud 是一系列框架的集合,用于开发分布式系统和微服务架构。它涵盖了负载均衡、服务发现、配置管理、分布式追踪等功能。
创建 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"; } }
MyBatis-Plus 是 MyBatis 的增强工具,它在 MyBatis 的基础上提供了大量的易用功能,如单表 CRUD 操作、分页、代码生成器等,旨在简化数据库操作。
添加依赖: 在 pom.xml
文件中添加 MyBatis-Plus 依赖。
xml
com.baomidou mybatis-plus-boot-starter 3.4.3.4
配置 MyBatis Plus:
java
@Configuration @MapperScan("com.example.mapper") public class MyBatisPlusConfig { }
编写 Mapper 接口:
java
public interface UserMapper extends BaseMapper { }
基本架构:
后端实现:
前端实现:
建立 Spring Boot 项目:
编写 RESTful 控制器:
java
@RestController @RequestMapping("/api") public class UserController { @Autowired private UserService userService; @GetMapping("/users") public List getAllUsers() { return userService.getAllUsers(); } }
建立前端项目(以 Vue.js 为例):
bash
vue create my-frontend cd my-frontend npm install axios
编写前端代码:
javascript
User List
- {{ user.name }}
Spring Security 是一个强大的安全框架,提供了全面的身份验证、授权与保护功能。它可以保护 Spring 应用免受常见的安全威胁。
添加依赖: 在 pom.xml
中添加 Spring Security 依赖。
xml
org.springframework.boot spring-boot-starter-security
编写配置类:
@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
Login Login
RabbitMQ 是一个消息队列中间件,广泛用于实现异步通信、消息传递、分布式系统中解耦和流量削峰。
bash
sudo apt-get update sudo apt-get install rabbitmq-server sudo systemctl enable rabbitmq-server sudo systemctl start rabbitmq-server
生产者代码:
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 -> { });
}
}
}
Apache Kafka 是一个分布式流处理平台,能够高效地发布和订阅消息,同时通过高容错性和高吞吐量支持大规模消息处理。
安装 Kafka: 访问 Kafka 官网下载并解压 Kafka。
启动 Zookeeper 和 Kafka:
bash
bin/zookeeper-server-start.sh config/zookeeper.properties bin/kafka-server-start.sh config/server.properties
生产者代码:
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 producer = new KafkaProducer<>(props);
for (int i = 0; i < 10; i++) {
String key = Integer.toString(i);
String value = "Hello Kafka " + i;
ProducerRecord 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 consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList("my-topic"));
while (true) {
ConsumerRecords records = consumer.poll(100);
for (ConsumerRecord record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
}
}
Redis 是一个开源的内存中数据结构存储系统,支持多种数据结构,如字符串、哈希、列表、集合、有序集合、位图和地理空间索引等。它常被用作数据库、缓存和消息中间件。
bash
sudo apt-get update sudo apt-get install redis-server sudo systemctl enable redis-server sudo systemctl start redis-server
添加 Jedis 依赖: 在 pom.xml
中添加 Jedis 依赖。
xml
redis.clients jedis 3.5.0
基本操作示例:
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(); } }
Elasticsearch 是一个分布式的搜索和分析引擎,可以实时地存储、搜索和分析海量数据。它建立在 Apache Lucene 之上,提供了 RESTful API 和分布式特性。
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
添加依赖: 在 pom.xml
中添加 Spring Data Elasticsearch 依赖。
xml
org.springframework.boot spring-boot-starter-data-elasticsearch
配置 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 { }
使用 Elasticsearch:
java
@Service public class ProductService { @Autowired private ProductRepository productRepository; public void saveProduct(Product product) { productRepository.save(product); } public Iterable 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 getAllProducts() { return productService.findAllProducts(); } }
MySQL 是全球最流行的开源关系型数据库管理系统,其广泛应用于 Web 应用开发中,具有高性能、可靠性和易用性。
安装 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
添加 JDBC 依赖: 在 pom.xml
中添加 MySQL 连接器依赖。
xml
mysql mysql-connector-java 8.0.23
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();
}
}
}
PostgreSQL 是一个功能强大、开放源代码的对象-关系型数据库系统,以其高可扩展性、强一致性以及对复杂查询的支持而广受欢迎。
bash
sudo apt-get update sudo apt-get install postgresql postgresql-contrib sudo systemctl start postgresql sudo systemctl enable postgresql
添加 JDBC 依赖: 在 pom.xml
中添加 PostgreSQL 连接器依赖。
xml
org.postgresql postgresql 42.2.18
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();
}
}
}
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
添加 MongoDB Java 驱动依赖: 在 pom.xml
中添加 MongoDB Java 驱动依赖。
xml
org.mongodb mongodb-driver-sync 4.3.3
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 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());
}
}
}
}
Neo4j 是一个高性能的、NOSQL 图形数据库,使用图数据模型储存数据。它非常适合用于复杂关系查询,例如社交网络、推荐系统等。
安装 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/
。
添加 Neo4j Java 驱动依赖: 在 pom.xml
中添加 Neo4j Java 驱动依赖。
xml
org.neo4j.driver neo4j-java-driver 4.2.5
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();
}
}
网络上的项目往往非常常见,建议去一些代码平台学习进一步的进行学习
在线商城系统:一个典型的在线商城系统,包括用户注册登录、商品展示、购物车、订单管理等模块。
博客系统:实现用户可以发表文章、评论、分类、标签等功能。
版本控制:使用 Git 进行版本控制,使用 GitHub 或 GitLab 进行协作管理。
编程规范和代码风格:遵循 Java 编码规范,提高代码的可读性和可维护性。
单元测试和集成测试:编写单元测试和集成测试,确保代码质量。
持续集成:使用 Jenkins 等持续集成工具,实现自动化构建和测试。
性能优化:使用缓存、数据库优化、内存管理等技术进行性能优化。
通过这篇详细的 Java 学习路线,你可以系统性地掌握 Java 基础、高级编程技术、热门框架、知名中间件和数据库技术。以下是学习路线的总结:
希望这篇文章能对你学习 Java 有所帮助,如果你有任何问题或建议,欢迎留言讨论。