Java主流框架教程:從入門到實戰
Java主流框架教程深入探索Java基础、Spring框架、MyBatis框架、Vue.js与Spring Boot集成以及RESTful API设计,全方位构建现代Web应用。从基础语法到框架应用,涵盖用户管理、账户操作等实际项目案例,旨在提升开发者对Java生态系统的整体理解和实践能力。
Java基础回顾在深入Java框架之前,先快速回顾一下Java的核心概念和语法基础,确保基础稳固。
基本语法示例
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
变量与类型
基本数据类型
public class DataTypes {
public static void main(String[] args) {
byte b = 10;
short s = 20000;
int i = 3000000;
long l = 4000000000L;
float f = 50.5f;
double d = 60.6d;
char c = 'A';
boolean b1 = true;
System.out.println(b + "\n" + s + "\n" + i + "\n" + l + "\n" + f + "\n" + d + "\n" + c + "\n" + b1);
}
}
控制结构
条件语句
public class ConditionalStatements {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("数字是正数");
} else if (num == 0) {
System.out.println("数字是零");
} else {
System.out.println("数字是负数");
}
}
}
循环结构
public class Loops {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("循环次数: " + i);
}
while (true) {
System.out.println("无限循环");
break; // 结束无限循环
}
}
}
函数与方法
public class Methods {
public static void main(String[] args) {
print("Hello from method");
System.out.println(checkNumber(42));
}
public static void print(String message) {
System.out.println(message);
}
public static boolean checkNumber(int num) {
return num > 0;
}
}
Spring Framework 解详
Spring框架是用于构建企业级应用的Java框架,其核心是依赖注入和面向切面编程(AOP)。接下来我们将通过简单示例来理解这些概念。
Spring Basic Configuration
首先,创建一个简单的Spring配置文件并定义一个Bean。
配置文件(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="greetingService" class="com.example.service.GreetingServiceImpl" />
</beans>
服务类(GreetingServiceImpl.java)
public class GreetingServiceImpl implements GreetingService {
@Override
public String sayHello() {
return "Hello from service!";
}
}
主类(Application.java)
public class Application {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
GreetingService greetingService = context.getBean("greetingService", GreetingService.class);
System.out.println(greetingService.sayHello());
}
}
AOP 示例
AOP切面(Aspect.java)
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("方法调用前: " + joinPoint.getSignature());
}
@After("execution(* com.example.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("方法调用后: " + joinPoint.getSignature());
}
}
MyBatis框架入门
MyBatis是一个优秀的持久层框架,它支持自定义SQL语句查询、存储过程以及高级映射。接下来,我们将通过一个简单的CRUD操作来介绍如何使用MyBatis。
配置文件(mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!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/db_name"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
映射文件(UserMapper.xml)
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="com.example.entity.User">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
</mapper>
服务类(UserMapper.java)
public interface UserMapper {
User getUserById(Integer id);
void insertUser(User user);
}
实现类(UserMapperImpl.java)
public class UserMapperImpl implements UserMapper {
@Override
public User getUserById(Integer id) {
// SQL查询实现
return null;
}
@Override
public void insertUser(User user) {
// SQL插入实现
}
}
Vue.js与Spring Boot集成
将Vue.js与Spring Boot结合,实现前后端分离的Web应用开发。下面是一个简单的示例,展示如何在Vue.js中调用Spring Boot API。
Vue.js组件(HelloWorld.vue)
<template>
<div>
<h1>{{ greeting }}</h1>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
greeting: ''
};
},
async mounted() {
await axios.get('/api/greeting')
.then(response => {
this.greeting = response.data.message;
})
.catch(error => {
console.error('Error fetching greeting:', error);
});
}
};
</script>
Spring Boot API(GreetingController.java)
@RestController
public class GreetingController {
@GetMapping("/api/greeting")
public GreetingResponse getGreeting() {
return new GreetingResponse("Hello from Spring Boot!");
}
}
请求响应类(GreetingResponse.java)
public class GreetingResponse {
private String message;
public GreetingResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
RESTful API设计
在Spring Boot中构建RESTful API,遵循RESTful原则设计接口,包括URL、HTTP方法和状态码。
RESTful API示例(UserController.java)
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable("id") Long id) {
return userService.findUserById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable("id") Long id, @RequestBody User user) {
return userService.updateUser(id, user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") Long id) {
userService.deleteUser(id);
}
}
实战项目构建
结合上述框架和知识,设计并实现一个完整的项目案例,以银行账户管理为例,涵盖用户管理、账户操作,以及前后端分离的Web应用开发全流程。
项目结构规划
- 数据库:设计账户用户表和账户表
- 前端:使用Vue.js实现用户交互界面
- 后端服务:基于Spring Boot实现RESTful API
本篇内容涵盖了Java基础回顾、Spring Framework、MyBatis框架入门、Vue.js与Spring Boot集成,以及RESTful API设计。通过实践示例,帮助读者深入理解并应用这些现代框架和工具。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章