引言
Java作为一门历史悠久且应用广泛的编程语言,拥有丰富的生态系统。Spring框架作为Java企业级开发的基石,已经帮助无数开发者简化了开发流程,提高了开发效率。本文将带你从零开始,深入了解Spring框架,并实战演练,助你成为Spring开发高手。
一、Spring框架概述
1.1 Spring框架简介
Spring框架是一个开源的Java企业级应用开发框架,由Rod Johnson在2002年首次发布。Spring框架旨在简化企业级应用开发,提供了一套完整的编程和配置模型,包括数据访问、事务管理、安全性、Web开发等。
1.2 Spring框架的核心模块
- Spring Core Container:提供核心功能,如依赖注入(DI)和面向切面编程(AOP)。
- Spring AOP:提供面向切面编程,允许在方法执行前后添加额外的逻辑。
- Spring Data Access/Integration:提供数据访问和集成功能,如JDBC、Hibernate、JPA等。
- Spring Web:提供Web应用开发支持,包括Servlet、JSP、REST等。
- Spring MVC:提供模型-视图-控制器(MVC)架构,用于开发Web应用。
- Spring Test:提供单元测试和集成测试支持。
二、Spring框架实战
2.1 创建Spring项目
- 选择IDE:推荐使用IntelliJ IDEA或Eclipse。
- 创建Maven项目:在IDE中创建一个Maven项目,并添加Spring依赖。
- 配置Spring配置文件:创建applicationContext.xml文件,配置Bean。
<?xml version="1.0" encoding="UTF-8"?>
<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="helloService" class="com.example.HelloService">
<property name="message" value="Hello, Spring!"/>
</bean>
</beans>
2.2 依赖注入
- 创建HelloService类。
public class HelloService {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 创建HelloController类。
public class HelloController {
@Autowired
private HelloService helloService;
public String sayHello() {
return helloService.getMessage();
}
}
- 配置Spring MVC。
<?xml version="1.0" encoding="UTF-8"?>
<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">
<context:component-scan base-package="com.example"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 创建hello.jsp页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello, Spring!</title>
</head>
<body>
<h1>${helloController.sayHello()}</h1>
</body>
</html>
2.3 AOP应用
- 创建一个切面类。
public class LoggingAspect {
@Before("execution(* com.example.HelloService.*(..))")
public void logBefore() {
System.out.println("Before method execution");
}
}
- 配置AOP。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:before pointcut="execution(* com.example.HelloService.*(..))" method="logBefore"/>
</aop:aspect>
</aop:config>
</beans>
2.4 数据访问
- 配置数据源。
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
- 创建JdbcTemplate类。
public class JdbcTemplateExample {
private JdbcTemplate jdbcTemplate;
public JdbcTemplateExample(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void executeQuery() {
List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM users");
for (Map<String, Object> row : rows) {
System.out.println(row);
}
}
}
- 配置JdbcTemplate。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
- 创建User类。
public class User {
private int id;
private String name;
// getters and setters
}
- 创建UserService类。
public class UserService {
private JdbcTemplate jdbcTemplate;
public UserService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<User> getAllUsers() {
return jdbcTemplate.query("SELECT * FROM users", (rs, rowNum) -> {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
return user;
});
}
}
- 配置UserService。
<bean id="userService" class="com.example.UserService">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
- 创建UserController类。
public class UserController {
@Autowired
private UserService userService;
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
- 配置UserController。
<bean id="userController" class="com.example.UserController">
<property name="userService" ref="userService"/>
</bean>
- 配置DispatcherServlet。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.web.servlet.DispatcherServlet">
<property name="contextConfigLocation" value="classpath:spring-mvc.xml"/>
</bean>
</beans>
- 创建users.jsp页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<ul>
<c:forEach var="user" items="${users}">
<li>${user.name}</li>
</c:forEach>
</ul>
</body>
</html>
- 配置Thymeleaf。
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver"/>
</bean>
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
- 创建UserController类。
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public String getAllUsers(Model model) {
model.addAttribute("users", userService.getAllUsers());
return "users";
}
}
三、总结
本文从零开始,介绍了Spring框架的基本概念、核心模块、实战应用以及AOP和数据访问。通过本文的学习,相信你已经对Spring框架有了深入的了解。在实际开发中,不断实践和总结,你将逐渐成为Spring开发高手。
