spring项目的常用示范

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 项目一些类的常用示范

项目pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>logindemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>logindemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.9</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>layui</artifactId>
            <version>2.7.6</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.21</version>
        </dependency>

        <!--        <dependency>-->
        <!--            <groupId>com.mysql</groupId>-->
        <!--            <artifactId>mysql-connector-j</artifactId>-->
        <!--            <scope>runtime</scope>-->
        <!--        </dependency>-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.github.taoyua</groupId>
            <artifactId>logindemo</artifactId>
            <version>0.0.1-RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
        </plugins>
    </build>

</project>

项目config配置:

SecrityConfig

import com.example.logindemo.service.LoginDetailsService;
import com.example.logindemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MySecritySuccessHandler mySecritySuccessHandler;

    @Autowired
    MySecrityFailureHandler mySecrityFailureHandler;

    @Autowired
    LoginDetailsService userDetailsService;

    @Autowired
    MySecrityLogoutHandler mySecrityLogoutHandler;

    @Autowired
    UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .headers().frameOptions().disable()
                .and().formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/form")
                .successHandler(mySecritySuccessHandler)
                .failureHandler(mySecrityFailureHandler)
                .and().authorizeRequests().antMatchers( "**/static/**","**/templates/**","/login")
                .permitAll()
                .anyRequest().authenticated();

        /**
         * 退出处理,logoutSuccessurl退出成功跳转登录
         */
        http.logout().logoutUrl("/signout").deleteCookies("JSESSIONID")//清除cookies
                .logoutSuccessHandler(mySecrityLogoutHandler);
//                .logoutSuccessUrl("/login").invalidateHttpSession(true);

    }

    /**
     * 忽略静态资源访问控制
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/css/**","/api/**","/images/**","/page/**",
                "/lib/**","/layui/**","/js/**","/*.js","/*.css","/*.png");
    }


    /**
     * 登录逻辑实现,获取数据库账号密码
     */

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 内存处理用户名及密码
     */
//    @Autowired
//    public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
//        auth.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("admin")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("USER");
//    }

//   密码加密
    //    public static void main(String[] args) {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        boolean matches = bCryptPasswordEncoder.matches( "123456","$2a$10$.y6yRGGU6uXyrq0Ftmdb9.WSZTZPZJmnoisz0IxaiRqvjPKUcywjq");
//        System.out.println(matches);
//        System.out.println(new BCryptPasswordEncoder().encode("123456"));

}

MySecritySuccessHandler:

import com.alibaba.fastjson2.JSON;
import com.example.logindemo.entity.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MySecritySuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Result result = new Result();
        result.setRespcode("0000");
        result.setRespmsg("登录成功");
        String res = JSON.toJSONString(result);
        httpServletResponse.getWriter().print(res);
    }
}

MySecrityFailureHandler:

import com.alibaba.fastjson2.JSON;
import com.example.logindemo.entity.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MySecrityFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Result result = new Result();
        result.setRespcode("1111");
        result.setRespmsg("登录失败!");
        String res = JSON.toJSONString(result);
        httpServletResponse.getWriter().print(res);
    }
}

MySecrityLogoutHandler:

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MySecrityLogoutHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login");//重定向到login

    }
}

控制类controller如下:

LoginController:

import com.example.logindemo.service.LoginDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    @Autowired
    LoginDetailsService loginDetailsService;


    @RequestMapping("/login")
    public String login1(){
        return "login";

    }

//    @PostMapping("/login")
//    public Result login1(String username, String password, HttpServletRequest request){
//        return loginDetailsService.loadUserByUsername(username);
//
//    }

    @RequestMapping("/signout")
    public String signout(){
        return "login";

    }

    @RequestMapping("/index")
    public String index(){
        return "index";

    }

    @RequestMapping("/main")
    public String main(){
        return "main";

    }

}

UserController:

import com.alibaba.fastjson2.JSONObject;
import com.example.logindemo.entity.User;
import com.example.logindemo.service.MenuService;
import com.example.logindemo.service.RoleService;
import com.example.logindemo.service.UserService;
import com.example.logindemo.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    RoleService roleService;

    @Autowired
    UserService userService;

    @Autowired
    MenuService menuservice;

    @GetMapping("/menus")
    @ResponseBody
    public Map<String, Object> menus() {
        String loginUsername = CommonUtils.getLoginUser();
        User loginUser = userService.findUserByusername(loginUsername);
        JSONObject initjson=new JSONObject(menuservice.menu(loginUser.getId()));

        return initjson;
    }

}

实体类entity:

Menu:

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.util.List;

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Menu {
    private Long id;

    private Long pid;

    private String title;

    private String icon;

    private String href;

//    private String target;

    private List<Menu> children;
}

Role:

import lombok.Data;

@Data
public class Role {
    private long id;
    private String name;

    //角色编码
    private String sn;

    //角色描述
    private String desc;

}

User:

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
    private String tel;
    private String sex;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private String createTime;


}

Result类

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

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private String respcode;
    private String respmsg;

}

mapper类如下:

MenuMapper:

import com.example.logindemo.entity.Menu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface MenuMapper {

    @Select("SELECT sr.id,sr.pid pid,sr.title,sr.icon,sr.href\n" +
            "FROM treemenu sr where STATUS = 1  ORDER BY  sort")
    List<Menu> ListPermissionByuserid(long userid);


    @Select("SELECT sr.id,sr.pid pid,sr.title,sr.icon,sr.href,sr.target FROM treemenu sr")
    List<Menu> listMenuByRoleid(long id);

//    @Select("SELECT sr.id,sr.pid pid,sr.title,sr.icon,sr.href,sr.target\n" +
//            "FROM sys_resources sr\n" +
//            "join role_treemenu st on st.menu_id=sr.id\n" +
//            "and st.role_id=#{id}")
//    List<MenuVo> listMenuByRoleid(long id);
}

RoleMapper:

import com.example.logindemo.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface RoleMapper {

    @Select("SELECT r.*\n" +
            "from role r\n" +
            "JOIN t_user_role u on r.id=u.roleid\n" +
            "where u.userid=#{userid}")
    List<Role> listRoleByuserid(long userid);//根据userID,查询该用户的角色
}

UserMapper:

import com.example.logindemo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("select *from admin where username=#{username}")
    User findUserByusername(String username);
}

service中的Impl实现类:

LoginDetailsService

import com.example.logindemo.entity.Role;
import com.example.logindemo.entity.User;
import com.example.logindemo.service.RoleService;
import com.example.logindemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class LoginDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//获取数据库用户
        User user= userService.findUserByusername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }else{
//            log.info("查到用户");
            Set authorities=new HashSet<>();
//            List<Role> roles = roleService.listRoleByuserid(user.getId());
//            for(Role role:roles) {
//                authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
//            }
            authorities.add(new SimpleGrantedAuthority("Role_管理员"));
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                    true,true,true,true,authorities);
        }

    }

}

MenuService:

import com.example.logindemo.entity.Menu;
import com.example.logindemo.entity.Role;
import com.example.logindemo.mapper.MenuMapper;
import com.example.logindemo.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;


@Service
public class MenuService {
    @Resource
    MenuMapper menuMapper;

    @Resource
    RoleService roleService;

    public Map<String, Object> menu(Long userid) {
        /**
         * 根据用户id获取用户所有角色
         */
//
//        List<Role> roleidList = roleService.listRoleByuserid(userid);
//        /**
//         * 遍历所有角色,获取list菜单
//         */
//        Set<Menu> menuSet=new HashSet<>();
//        for(Role role:roleidList){
//            List<Menu> sysMenuList = menuMapper.listMenuByRoleid(role.getId());
//            for(Menu menu :sysMenuList){
//                menuSet.add(menu);
//            }
//
//        }
//        List<Menu> sysmenuList=new ArrayList<>(menuSet);
        //将菜单转为权限树
        List<Menu> menuInfo=menuMapper.ListPermissionByuserid(userid);
        List<Menu> menuTree = new ArrayList<>();
        menuTree= TreeUtil.toTree(menuInfo, 0L);
        Map<String, Object> map = new HashMap<>();
        map.put("data", menuTree);
        return map;
    }

}

RoleService:

import com.example.logindemo.entity.Role;
import com.example.logindemo.mapper.RoleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleService {
    @Resource
    private RoleMapper roleMapper;

    public List<Role> listRoleByuserid(long userid) {
        List<Role> roles = roleMapper.listRoleByuserid(userid);
        return roles;
    }
}

UserService:

import com.example.logindemo.entity.User;
import com.example.logindemo.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {

    @Resource
    UserMapper usermapping;

    public User findUserByusername(String username) {

        return usermapping.findUserByusername(username);
    }

}

utils工具类:

CommonUtils:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class CommonUtils {
    public static String getLoginUser(){
        //获取登录认证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //得到认证的主体(登录用户)

        if(authentication!=null) {
            return authentication.getName();
        }
        return null;
    }
}

TreeUtil:

import com.example.logindemo.entity.Menu;
import java.util.ArrayList;
import java.util.List;

public class TreeUtil {
    public static List<Menu> toTree(List<Menu> treeList, Long pid) {
        List<Menu> retList = new ArrayList<Menu>();
        for (Menu parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }
    private static Menu findChildren(Menu parent, List<Menu> treeList) {
        for (Menu child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }

}

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#云上
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://rm-bp1l57prt0jm1g81x.mysql.rds.aliyuncs.com:3306/manage_system?characterEncoding=utf8
spring.datasource.username=yt
spring.datasource.password=Yt@123456

spring.web.resources.static-locations=classpath:/static/,/templates/

spring.thymeleaf.cache=false

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
7天前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
19 2
|
1月前
|
设计模式 前端开发 Java
Spring MVC——项目创建和建立请求连接
MVC是一种软件架构设计模式,将应用分为模型、视图和控制器三部分。Spring MVC是基于MVC模式的Web框架,通过`@RequestMapping`等注解实现URL路由映射,支持GET和POST请求,并可传递参数。创建Spring MVC项目与Spring Boot类似,使用`@RestController`注解标记控制器类。
34 1
Spring MVC——项目创建和建立请求连接
|
1月前
|
Java 关系型数据库 MySQL
Maven——创建 Spring Boot项目
Maven 是一个项目管理工具,通过配置 `pom.xml` 文件自动获取所需的 jar 包,简化了项目的构建和管理过程。其核心功能包括项目构建和依赖管理,支持创建、编译、测试、打包和发布项目。Maven 仓库分为本地仓库和远程仓库,远程仓库包括中央仓库、私服和其他公共库。此外,文档还介绍了如何创建第一个 SpringBoot 项目并实现简单的 HTTP 请求响应。
117 1
Maven——创建 Spring Boot项目
|
1月前
|
Java 关系型数据库 MySQL
如何使用 maven 创建一个 Spring Boot项目
Maven 是一个强大的项目管理工具,通过配置 `pom.xml` 文件自动获取所需的 jar 包,提高开发效率。其核心功能包括项目构建和依赖管理。项目构建支持编译、测试、打包和发布等流程,而依赖管理则通过中央仓库、本地仓库和私有服务器获取和管理项目依赖。示例中展示了如何创建第一个 SpringBoot 项目并实现简单接口。
26 1
如何使用 maven 创建一个 Spring Boot项目
|
4月前
|
Java 测试技术 数据库
Spring Boot中的项目属性配置
本节课主要讲解了 Spring Boot 中如何在业务代码中读取相关配置,包括单一配置和多个配置项,在微服务中,这种情况非常常见,往往会有很多其他微服务需要调用,所以封装一个配置类来接收这些配置是个很好的处理方式。除此之外,例如数据库相关的连接参数等等,也可以放到一个配置类中,其他遇到类似的场景,都可以这么处理。最后介绍了开发环境和生产环境配置的快速切换方式,省去了项目部署时,诸多配置信息的修改。
|
1月前
|
Java 应用服务中间件 Android开发
Eclipse创建Spring项目
本文介绍了在Eclipse中创建Spring项目的步骤,包括如何配置Tomcat服务器、创建项目、部署项目到Tomcat以及添加Spring框架所需的JAR包。
53 1
Eclipse创建Spring项目
|
1月前
|
Java Spring
ij社区版如何创建spring项目
如何在IntelliJ IDEA社区版中创建Spring项目,包括安装Spring Boot Helper插件的步骤和创建过程。
66 1
ij社区版如何创建spring项目
|
1月前
|
Java Apache Maven
Java/Spring项目的包开头为什么是com?
本文介绍了 Maven 项目的初始结构,并详细解释了 Java 包命名惯例中的域名反转规则。通过域名反转(如 `com.example`),可以确保包名的唯一性,避免命名冲突,提高代码的可读性和逻辑分层。文章还讨论了域名反转的好处,包括避免命名冲突、全球唯一性、提高代码可读性和逻辑分层。最后,作者提出了一个关于包名的问题,引发读者思考。
Java/Spring项目的包开头为什么是com?
|
1月前
|
前端开发 Java 应用服务中间件
【Spring】Spring MVC的项目准备和连接建立
【Spring】Spring MVC的项目准备和连接建立
54 2
|
1月前
|
XML Java 应用服务中间件
【Spring】运行Spring Boot项目,请求响应流程分析以及404和500报错
【Spring】运行Spring Boot项目,请求响应流程分析以及404和500报错
168 2