SpringBoot基础day04 - Service注解

SpringBoot基础day04 - Service注解

Tags: SpringBoot

摘要

SpringBoot基础day04 - Service注解

Service注解

注入业务类,把controller里的逻辑代码封装在ServiceBean里
并且把ServiceBean提取到一个接口里. 方便重写.

package app.service;

import app.model.User;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhu on 17-1-2.
 */
@Service
public class UserServiceBean implements UsersService {
    private static BigInteger nextId;
    private static Map<BigInteger, User> userMap;

    static {
        User user1 = new User();
        user1.setId(BigInteger.valueOf(1));
        user1.setAge(18);
        user1.setName("张三");

        User user2 = new User();
        user2.setId(BigInteger.valueOf(2));
        user2.setAge(28);
        user2.setName("李四");

        if (userMap == null) {
            userMap = new HashMap<BigInteger, User>();
        }
        userMap.put(user1.getId(), user1);
        userMap.put(user2.getId(), user2);
        nextId = BigInteger.valueOf(3);
    }

    //模拟保存,更新
    private static User save(User user) {
        if (userMap == null) {
            userMap = new HashMap<BigInteger, User>();
            nextId = BigInteger.ONE;
        }

        if (user.getId() != null) {
            User u = userMap.get(user.getId());
            if (u == null) {
                return null;//指定更新不存在
            }
            userMap.remove(user.getId());
            userMap.put(user.getId(), user);
            return user;
        }
        user.setId(nextId);
        nextId = nextId.add(BigInteger.ONE);
        userMap.put(user.getId(), user);
        return user;
    }


    private static boolean remove(BigInteger id) {
        User user = userMap.remove(id);
        if (user == null) {
            return false;
        }
        return true;
    }


    @Override
    public Collection<User> findAll() {
        Collection<User> users = userMap.values();
        return users;
    }

    @Override
    public User findOne(long id) {
        User user = userMap.get(BigInteger.valueOf(id));
        return user;
    }

    @Override
    public User create(User user) {
        User saveuser = save(user);
        return saveuser;
    }

    @Override
    public User update(User user) {
        User updateuser = save(user);
        return updateuser;
    }

    @Override
    public void delete(long id) {
        remove(BigInteger.valueOf(id));
    }
}

Autowired注入

使用的时候在Controller里如下使用

    @Autowired
    private UsersService usersService;

代码地址

https://coding.net/u/javacore/p/spring-boot-fundamentals/git/tree/master/day04