文章目录
Re:从零开始的Spring入门(一)(图文并茂)
Spring 是分层的 full-stack(全栈) 轻量级开源框架,以 IoC 和 AOP 为内核,提供了展现层 SpringMVC 和业务层事务管理等众多的企业级应⽤技术,还能整合开源世界众多著名的第三⽅框架和类库,已经成为使⽤最多的 Java EE 企业应⽤开源框架。
Spring 官⽅⽹址:http://spring.io/
我们经常说的 Spring 其实指的是Spring Framework(spring 框架)。
先从创建一个简单的项目开始吧!
一、创建项目
创建项目之前,确保java环境已搭建
Java开发环境搭建
1)NewProject
设置项目信息:
完成创建:
2)导入Spring依赖
<!--引入spring IoC容器功能-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring web功能-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring声明式事务相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--第三方的aop框架aspectj的jar-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>runtime</scope>
</dependency>
二、创建实体类
1)安装lombok插件
lombok插件 和 lombok依赖 缺一不可
2)导入lombok依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
@Data 注解
- 所有属性的get和set方法
- toString 方法
- hashCode方法
- equals方法
@NoArgsConstructor 创建无参构造函数
3)创建实体类
package com.lagou.pojo;
@Data
@NoArgsConstructor
public class Account {
private String cardNo;
private String name;
private int money;
}
4)创建sql表
CREATE TABLE `account` (
`cardNo` varchar(100) NOT NULL COMMENT '银行卡号',
`name` varchar(255) DEFAULT NULL COMMENT '用户名',
`money` int(11) DEFAULT NULL COMMENT '账户金额',
PRIMARY KEY (`cardNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `account` VALUES ('6029621011000', '李大雷', 1000);
INSERT INTO `account` VALUES ('6029621011001', '韩梅梅', 1000);
三、创建IoC容器
1)创建 applicationContext
resource 下创建 applicationContext.xml:
<?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 ">
</beans>
2)导入数据库
导入依赖
<!--数据库驱动包-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!--druid连接池-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
创建 DataSource 和 JdbcTemplate 对象:
<?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 ">
<!--第三方jar中的bean定义在xml中-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置一个 JdbcTemplate 对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
</beans>
4)引入数据库配置文件
resource 下创建 jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bank?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
注意本地数据库的版本
--MySQL8.x
--驱动:com.mysql.cj.jdbc.Driver
--url:"jdbc:mysql://localhost:3306/database_name?characterEncoding=utf8&serverTimezone=UTC"
--MySQL5.x
--驱动:com.mysql.jdbc.Driver
--url:"jdbc:mysql://localhost:3306/database_name"
导入Context命名空间,开启注解扫描和引入外部资源:
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd ">
<!--引入外部资源文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--开启注解扫描,base-package指定扫描的包路径-->
<context:component-scan base-package="com.lagou"/>
//...
</beans>
四、创建接口
1)创建 AccountDao
public interface AccountDao {
Account queryAccountByCardNo(String cardNo) throws Exception;
int updateAccountByCardNo(Account account) throws Exception;
}
2)创建 AccountDaoImpl
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account queryAccountByCardNo(String cardNo) throws Exception {
String sql = "select * from account where cardNo=?";
return jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setName(resultSet.getString("name"));
account.setCardNo(resultSet.getString("cardNo"));
account.setMoney(resultSet.getInt("money"));
return account;
}
}, cardNo);
}
@Override
public int updateAccountByCardNo(Account account) throws Exception {
String sql = "update account set money=? where cardNo=?";
return jdbcTemplate.update(sql,account.getMoney(),account.getCardNo());
}
}
五、创建service
1)创建 AccountService
public interface AccountService {
int transfer(String fromCardNo,String toCardNo,int money) throws Exception;
}
2)创建 AccountServiceImpl
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
Account from = accountDao.queryAccountByCardNo(fromCardNo);
Account to = accountDao.queryAccountByCardNo(toCardNo);
from.setMoney(from.getMoney()-money);
to.setMoney(to.getMoney()+money);
int row1 = accountDao.updateAccountByCardNo(to);
//int c = 1/0;
int row2 = accountDao.updateAccountByCardNo(from);
return row1&row2;
}
}
六、单元测试
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)/*使用spring单元测试*/
@ContextConfiguration("classpath:applicationContext.xml")/*加载配置文件*/
public class AccountDaoTest {
@Autowired
private DataSource dataSource;
@Autowired
private AccountDao accountDao;
@Autowired
private AccountService accountService;
@org.junit.Test
public void dataSource() throws SQLException {
System.out.println(dataSource.getConnection());
}
@org.junit.Test
public void dao() throws Exception {
Account account = accountDao.queryAccountByCardNo("6029621011000");
System.out.println(account);
}
@org.junit.Test
public void service() throws Exception {
int transfer = accountService.transfer("6029621011000", "6029621011001", 1);
System.out.println(transfer);
}
}
七、创建Servlet
1)导入依赖
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--设置作用域 scope:provided
部署到tomcat的时候是不会把jar包打包到项目中的,
因为tomcat中已经有自己的一份ServletAPI,防止冲突-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
2)创建AccountServlet
@WebServlet(name = "accountServlet", urlPatterns = "/accountServlet")
public class AccountServlet extends HttpServlet {
@Autowired
private AccountService accountService;
/**
* servlet单独有一个容器,归tomcat管理
* @Autowired 无法注入 service
*/
@Override
public void init() throws ServletException {
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
accountService = (AccountService) webApplicationContext.getBean("accountService");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求体的字符编码
request.setCharacterEncoding("UTF-8");
String fromCardNo = request.getParameter("fromCardNo");
String toCardNo = request.getParameter("toCardNo");
String moneyStr = request.getParameter("money");
int money = Integer.parseInt(moneyStr);
Result result = new Result();
try {
// 调用service层方法
int transfer = accountService.transfer(fromCardNo, toCardNo, money);
result.setStatus("200");
} catch (Exception e) {
e.printStackTrace();
result.setStatus("201");
result.setMessage(e.toString());
}
// 响应
response.setContentType("application/json;charset=utf-8");
String s = JSON.toJSONString(result);
System.out.println(s);
Object o = JSON.toJSON(result);
System.out.println(o);
response.getWriter().print(o.toString());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
3)配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<!--加载spring的配置文件,去创建ioc容器,放到ServletContext域当中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--使用监听器启动Spring的IOC容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
九、运行项目
1)配置tomcat
设置Application context 项目名:
2)运行
浏览器输入
http://localhost:8080/accountServlet?money=1&fromCardNo=6029621011001&toCardNo=6029621011000
附录:
项目地址
https://gitee.com/yudonz/spring-anno.git
Tomcat安装
1.官网下载
下载解压到本地(目录不要带中文或者空格)
2.配置环境变量(可选)
CATALINA_HOME D:\Programs\apache-tomcat-9.0.39
path %CATALINA_HOME%\bin;
cmd运行 startup.bat
浏览器输入一下 http://localhost:8080
3.8080端口占用问题
可以杀死占用进程 或者 修改tomcat端口号
- 杀死占用进程
netstat -ano|findstr 8080 //查找进程号
taskkill /pid 1524 /f //杀死进程号
- 修改端口号
修改 Tomcat --> conf --> server.xml 文件,第69行
<Connector port="8888" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
4.启动乱码问题
修改 Tomcat --> conf --> logging.properties
将所有 UTF-8 改成 GBK