spring

@SpringBootApplication

包含了@SpringBootConfiguration、@ComponentScan和@EnableAutoConfiguration

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@SpringBootConfiguration

用于标注在主类上,底层是@Configuartion

@ComponentScan

组件扫描,可自动发现和装配一些bean。

@EnableAutoConfiguration

组件扫描,可自动发现和装配一些bean。

@Configuration

声明一个类为配置类,将该类作为bean交给spring容器管理

/**
 * @desc Swagger配置类
 * @createdate 2019/9/27
 */
@Configuration  //让spring来加载该类配置
@EnableSwagger2 //启用Swagger2
public class Swagger2 {

    /**
     * 创建API应用
     * createApiInfo() 增加api相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现
     * 采用指定扫描的包路径来定义指定要建立API的目录
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(createApiInfo())
                .select()
                //暴露给Swagger的包路径
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息
     * 访问地址:http://localhost:8080/swagger-demo/swagger-ui.html
     *
     * @return
     */
    protected ApiInfo createApiInfo() {
        return new ApiInfoBuilder()
                //标题
                .title("SpringBoot Restful APIs")
                //标题下方的小字
                .description("项目API")
                //组织服务地址
                .termsOfServiceUrl("https://swagger.io/resources/open-api/")
                //开发者
                .contact("")
                //API版本
                .version("1.0")
                .build();
    }
}

@Component

将一个类声明为bean,交由spring容器管理

@Component
public class EmailUtils {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sender;

    public void simpleSend(String receiver, String subject, String content) throws Exception {

        if (receiver == null || receiver.equals("")) {
            throw new Exception("接收方错误!");
        }
        if (subject == null || subject.equals("")) {
            throw new Exception("标题错误");
        }
        if (content == null) {
            content = "";
        }

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom(sender);//发送者
        msg.setTo(receiver);//接收者
        msg.setSubject(subject);//标题
        msg.setText(content);//内容
        javaMailSender.send(msg);
    }
}

@RestController

包含@Controller和@ResponseBody

@Api(value = "用户权限访问", description = "用户模块")
@RestController
@RequestMapping("/userAPI/user")
public class UserController {
    @GetMapping("/index")
    public JsonData index() {
        return JsonData.buildSuccess("成功");
    }
}

@RequestMapping/@GetMapping/@PostMapping

用于设置访问路径,如下,若要访问index方法,路径应当为localhost:8080/userAPI/user/index

@Api(value = "用户权限访问", description = "用户模块")
@RestController
@RequestMapping("/userAPI/user")
public class UserController {
    @GetMapping("/index")
    public JsonData index() {
        return JsonData.buildSuccess("成功");
    }
}

springMVC

@Controller

声明一个类是控制器并交由spring容器管理

@ResponseBody

用于返回Restful风格的数据(json数据)

@Autowired

自动导入bean,用于使用spring容器中的bean
如下,下面就说明这个类可以使用UserService这个类了(UserService使用@Service标注过,已经交由spring容器管理)

@Autowired
private UserService userService;

@Service

声明一个service层的类并将其交由spring容器管理

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Person findAllUserInfoByUserId(int userId) {
        User user = userMapper.selectByUserID(userId);
        List<Identity> identities = roleMapper.findRoleListByUserId(userId);
        return new Person(user, identities);
    }

    @Override
    public User registerUser(User user) {
        String hashName = "md5";
        String pwd = user.getPassword();
        Object result = new SimpleHash(hashName, pwd, null, 2);
        user.setPassword(String.valueOf(result));
        userMapper.insert(user);

        Role role = roleMapper.selectByRoleName("user");
        UserRole userRole = new UserRole(user.getUserId(), role.getRoleId());

        userRoleMapper.insert(userRole);
        return user;
    }

    @Override
    public User findById(int userId) {
        return userMapper.selectByUserID(userId);
    }

    @Override
    public Person alreadyLogin() {
        Object object = SecurityUtils.getSubject().getPrincipal();
        if (object != null && !object.equals("")) {
            int userID = Integer.parseInt(String.valueOf(object));
            return findAllUserInfoByUserId(userID);
        }
        return null;
    }

    @Override
    public boolean existEmail(String email) {
        return userMapper.existEmail(email) != 0;
    }
}

mybatis

@Mapper

用于声明一个dao接口并将其交由spring容器管理

@Param

用于将参数映射到sql语句中

@Select("select * from user where userId=#{userId}")
User selectByUserID(@Param("userId") int userId);

@Select

标注一个方法所对应的的查询语句

@Update

标注一个方法锁对应的更新语句

@Delete

标注一个方法所对应的删除语句

@Insert

标注一个方法所对应的增加语句

Options

用于标注语句的其他操作,下面这个例子就是返回自增后的主键id

@Insert("insert into user(password,email) values(#{password},#{email})")
@Options(useGeneratedKeys = true, keyProperty = "userId", keyColumn = "userId")
void insert(User user);

@Results&@Result&@Many&@One

用于一对一、一对多、多对一、多对多查询
如下面这个例子(RBAC0权限模型),首先找到用户id所对应的角色集合(角色id、角色名称),之后根据角色id找到对应的权限集合(权限id、权限名称、权限url)

@Select("select ur.roleId as id, " +
        "r.roleName as name" +
        " from  userRole ur left join role r on ur.roleId = r.roleId " +
        "where  ur.userId = #{userId}")
@Results(
        value = {
                @Result(id = true, property = "id", column = "id"),
                @Result(property = "name", column = "name"),
                @Result(property = "permissionList", column = "id",
                        many = @Many(select = "com.example.demo.user.dao.PermissionMapper.findPermissionListByRoleId", fetchType = FetchType.DEFAULT)
                )
        }
)
List<Identity> findRoleListByUserId(@Param("userId") int userId);

@Select("select p.permissionId as permissionId, p.permissionName as permissionName, p.url as url from  rolePermission rp " +
            "left join permission p on rp.permissionId=p.permissionId " +
            "where  rp.roleId=#{roleId}")
List<Permission> findPermissionListByRoleId(@Param("roleId") int roleId);