从零开始写类似Spring和SpringBoot的框架

Toy-Spring

简介

快速链接

源码下载 https://gitee.com/fencer911/toy-spring

1. ToySpring是一款轻量级 类SpringBoot框架,模仿spring,spring mvc ,SpringBoot 参考了部分代码

  • 内置 IOC、MVC 等特性
  • 和spring boot类似,集成tomcat 但没实现spring boot 的自动配置功能
  • 基于 Servlet 3.0 规范
  • 使用 Java 注解取代 XML 配置 可以使用Configuration,Bean注解配置java bean

2. 对开发新手来说,可以借此了解学习研究真的Spring框架

  • 基于 学习目的创造次轮子,Spring的代码太容易让人头晕
  • mvc模块使用了很多Spring里的接口,但实现做了大幅的改造简化
  • 持续增加一些类SpringBoot里的特性,但立足于简洁明了

入门

1. 创建一个 Maven Web 工程

整个工程的目录结构如下:

topspring-sample/
  ┗ src/
    ┗ main/
      ┗ java/
      ┗ resources/
            ┗ application.properties
            ┗ log4j.properties
            ┗ templates
              ┗ index.html
  ┗ pom.xml

java 目录下,创建以下包名目录结构:

toy/
  ┗ spring/
    ┗ sample/
      ┗ action/
      ┗ entity/
      ┗ service/
          ┗ App.java 

2. 配置 Maven 依赖

1.下载 [email protected]:fencer911/toy-spring.git 源码 mvn install 到本地

2.编辑 pom.xml 文件,添加 ToySpring 依赖:

<dependency>
    <groupId>org.niugroupId>
    <artifactId>toy-springartifactId>
    <version>2.0-SNAPSHOTversion>
dependency>

提示:在jdk1.8下做的开发和测试,其他版本效果未知

3. 编写 ToySpring 配置

resources 目录下,创建一个名为 application.properties 的文件,内容如下:

### Default web context path:
server.servlet.contextPath=/toy-spring
### Default web server port:
server.port=8080

提示:需根据实际情况修改以上配置。

4. 编写 Entity 类

package toy.spring.sample.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
}

5. 编写 Service 接口及其实现

Service 接口

package toy.spring.sample.service;

import niu.toy.sample.entity.User;
import java.util.List;

public interface UserService {

    List<User> findUserList();

    User findUser(long id);

    boolean saveUser(User newUser);

    boolean updateUser(User updateUser);

    boolean deleteUser(long id);
}

Service 实现

package toy.spring.sample.service.impl;

import cn.hutool.core.bean.BeanUtil;
import niu.toy.sample.entity.User;
import niu.toy.sample.service.UserService;
import niu.toy.spring.ioc.annotation.Service;
import niu.toy.spring.tx.annotation.Transaction;

import java.util.ArrayList;
import java.util.List;

/**
 * 基于演示目的 数据放内存
 * @author niu
 */
@Service
public class UserServiceImp implements UserService {
    private  List<User> users=new ArrayList<>();

    @Override
    public List<User> findUserList() {
        return users;
    }

    @Override
    public User findUser(long id) {
        return users.stream().filter(u->u.getId()==id).findFirst().orElse(null);
    }

    @Override
    @Transaction
    public boolean saveUser(User newUser) {
        return users.add(newUser);
    }

    @Override
    @Transaction
    public boolean updateUser(User updateUser) {
        User oldUser=this.findUser(updateUser.getId());
        if(oldUser!=null){
            BeanUtil.copyProperties(updateUser,oldUser);
            return true;
        }
        return false;
    }

    @Override
    @Transaction
    public boolean deleteUser(long id) {
        User oldUser=this.findUser(id);
        if(oldUser!=null){
            return this.users.remove(oldUser);
        }
        return false;
    }
}

5. 编写 Action 类

package toy.spring.sample.action;

import niu.toy.sample.entity.User;
import niu.toy.sample.service.UserService;
import niu.toy.spring.ioc.annotation.Autowired;
import niu.toy.spring.mvc.annotation.*;

/**
 * 为了测试mvc 的参数解析转换功能 add方法有3个版本分别对应不同的参数解析方式
 * @author niu
 */
@Action
public class UserAction {
    @Autowired
    private UserService userService;

    @Request.Get("/user")
    public String index() {
        return "index";
    }

    @Request.Get("/user/list")
    @ResponseBody
    public Object list() {
        return userService.findUserList();
    }

    @Request.Get("/user/add")
    @ResponseBody
    public Object add(@RequestParam String name, Integer age, Long id) {
        return userService.saveUser(new User(id,name,age,null));
    }
    @Request.Get("/user/add2")
    @ResponseBody
    public Object add2(User user) {
        return userService.saveUser(user);
    }
    @Request.Post("/user/add3")
    @ResponseBody
    public Object create3(@RequestBody User user) {
        return userService.saveUser(user);
    }
    @Request.Get("/user/del")
    public String del(Long id) {
        userService.deleteUser(id);
        return "redirect:/user";
    }
}

6. 编写 启动类

启动类和SpringBoot类似

package toy.spring.sample;


import niu.toy.spring.boot.SpringApplication;
import niu.toy.spring.boot.annotation.SpringBootApplication;
import niu.toy.spring.mvc.WebApplicationContext;

@SpringBootApplication
public class App {
    public static void main(String[] args) throws Exception {
        WebApplicationContext ctx=SpringApplication.run(App.class);
    }
}

参考资料

  • Smart 系列博文:http://my.oschina.net/huangyong/blog/158380
  • SpringBoot 源码

你可能感兴趣的:(从零开始,spring,spring,boot,java,写框架,mvc)