03)java spi应用 java spring web项目 去除web.xml

本文介绍如何在没有web.xml的情况下,使用Spring框架进行项目配置。包括利用Maven搭建项目、配置依赖、理解Spring的ServletContainerInitializer实现及WebApplicationInitializer接口的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

上一节 学习完了 原始 java web项目 无web.xml怎么配置servlet

这节学习 java web项目 无web.xml怎么集成spring框架

 

使用过web.xml集成spring框架的同学应该对下面2个web.xml的配置都熟悉

 

spring的ContextLoaderListener监听器实现了ServletContextListener监听器

在web应用启动时会自动执行contextInitialized方法,寻找spring的配置文件application.xml,完成spring容器的启动工作

web.xml配置springmvc DispatcherServlet 如下,去除web.xml后  都需要有对应的解决方案

好了,下面开始学习去除web.xml的集成spring的方法

 

1. 新建一个maven web项目 

上一节普通java web项目保留 ,新建一个maven web项目,建好后先删除web.xml文件

 

2.pom.xml引入spring依赖

pom.xml如下 使用的是spring  4.3.12 正式版本

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wying</groupId>
  <artifactId>JavaSpringWebNoWebxmlDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>JavaSpringWebNoWebxmlDemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>4.3.12.RELEASE</spring.version>
  </properties>

  <dependencies>
    <!-- 引入 servlet-api.jar scope设置为provided
   不会打包到项目lib,项目在tomcat运行时 tomcat lib下已经有servlet-api.jar-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>




  </dependencies>

  <build>
    <finalName>JavaSpringWebNoWebxmlDemo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

3.spring 去除web.xml原理

普通java web项目META-INF/service我们配置的javax.servlet.ServletContainerInitializer是指向的自己写的实现类

 使用spring框架,spring已经提供了实现类,并且spring-web  META-INF/service 配置好了javax.servlet.ServletContainerInitializer,指向了spring的实现类,这样tomcat启动时就会执行spring实现类的onStartup方法

 

spring实现类位于  spring-web-4.3.12.RELEASE.jar  org.springframework.web.SpringServletContainerInitializer

查看spring源码,该类org.springframework.web.SpringServletContainerInitializer实现了servlet-api的ServletContainerInitializer接口

 

并且class上有一个@HandlesTypes({WebApplicationInitializer.class})注解,是servlet提供的javax.servlet.annotation.HandlesTypes,它配置的value为WebApplicationInitializer.class}

查看源码可以发现onStart会寻找HandlesTypes配置的class的子类,并执行WebApplicationInitializer子类的onStartup方法

这其实也很好理解 META-INF/service javax.servlet.ServletContainerInitializer是指向的spring的实现类,这个是编译成class的,我们无法修改,但是我们肯定是要写自己的逻辑的,所以通过HandlesTypes扩展

比如加载spring配置文件,启动spring容器,配置spring mvc DispatcherServlet, 配置普通的servlet 监听器等,

 

 

 

4.查看spring-web自带配置META-INF/service  javax.servlet.ServletContainerInitializer文件

有个警告,idea还是比较智能的,因为SpringServletContainerInitializer实现了ServletContainerInitializer.class,不引入servlet-api.jar找不到ServletContainerInitializer.class

 

pom.xml引入servlet-api.jar ,警告消失

  <!-- 引入 servlet-api.jar scope设置为provided
   不会打包到项目lib,项目在tomcat运行时 tomcat lib下已经有servlet-api.jar-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

 

 

5.先启动tomcat测试一波

 

因为我们还没编写实现WebApplicationInitializer的类, initializers.isEmpty()执行为true,将输入以下日志

但是我idea debug class进入了,server没打印出这个log,因为servletContext.log是打印在Tomcat Localhost Log中

6.一步一步来,接下来编写 class 实现WebApplicationInitializer.class

MySpringInitializer.class

package com.wying.web;

import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * description:编写实现类 实现WebApplicationInitializer
 * 这样tomcat启动时 先执行SpringServletContainerInitializer.class的onStartup方法
 * 在通过HandlesTypes配置 执行该class的onStartup方法
 * date: 2021/3/19
 * author: gaom
 * version: 1.0
 */

public class MySpringInitializer  implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("=========MySpringInitializer onStartup============");
        System.out.println("=========MySpringInitializer 启动spring容器============");
         // 代替 web.xml 中的 listener 初始化
         //<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        AnnotationConfigWebApplicationContext ac_spring = new AnnotationConfigWebApplicationContext();
        // listener中的加载spring.xml的配置文件内容 MySpringXml.class代替 spring.xml
        ac_spring.register(MySpringXml.class);
        //用于初始化spring配置文件 web项目可用可不用

        servletContext.addListener(new ContextLoaderListener(ac_spring));
        System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");
        AnnotationConfigWebApplicationContext ac_mvc = new AnnotationConfigWebApplicationContext();
        //MySpringMvcXml.class代替 spring-mvc.xml
        ac_mvc.register(MySpringMvcXml.class);
        //用于初始化spring配置文件 web项目可用可不用

        //配置spring dispatcherServlet  代替web.xml
        // <servlet-name>springDispatcher</servlet-name>
        //<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ac_mvc);
        //创建前端控制器去名字为dispatcherServlet  <servlet>标签
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        //启动顺序设置为1 tomcat启动时就初始化该servlet
        registration.setLoadOnStartup(1);
        //<servlet-mapping>里面的url-patten
        registration.addMapping("*.do");
        System.out.println("=========MySpringInitializer onStartup 运行完毕============");

    }
}

MySpringXml.class

package com.wying.web;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


/**
 * 相当于spring.xml文件
 * description:spring提供了使用代码去除 spring.xml配置文件的方式
 * 、。。既然servlet3.0 开始都去除web.xml了 spring也提供了一套去除自家xml配置的方法
 * 该class通过代码配置xml的内容
 * date: 2021/3/19
 * author: gaom
 * version: 1.0
 */

@Configuration
@ComponentScan(basePackages = "com.wying")
public class MySpringXml {


    //目前测试效果 不连接数据库
    // 配置datasource sessionFactory 也一样 通过@Bean注解 规则都差不多 xml的配置 都有对应的class method对应
}

 

MySpringMvcXml.class

package com.wying.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**相当于spring-mvc.xml文件
 * description:spring提供了使用代码去除 spring-mvc.xml配置文件的方式
 * 、。。既然servlet3.0 开始都去除web.xml了 spring也提供了一套去除自家xml配置的方法
 * 该class通过代码配置spring-mvc.xml的内容
 * date: 2021/3/19
 * author: gaom
 * version: 1.0
 */

@Configuration
@EnableWebMvc  //开启支持mvc
@ComponentScan(basePackages = "com.wying")
public class MySpringMvcXml {

    /**
     * 代替spring-mvc.xml
     * <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolve">
     * @return
     */
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }


}
TestController.class

新建一个controller,用于测试spring-mvc DispatcherServlet是否配置成功

package com.wying.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * description:测试controller
 * date: 2021/3/19
 * author: gaom
 * version: 1.0
 */
@Controller
public class TestController {
    @RequestMapping(value="test.do")
    public String testjsp(){
        return  "test";
    }
}

7.tomcat启动项目

成功打印出spring初始化日志

浏览器测试效果

http://localhost:8082/JavaSpringWebNoWebxmlDemo_war_exploded/访问项目根目录成功读取默认的index.jsp文件

http://localhost:8082/JavaSpringWebNoWebxmlDemo_war_exploded/test.do 测试controller,成功读取到jsp页面

 

8.使用spring.xml文件

 

目前已经实现去除web.xml和spring的所有配置文件,但是实际项目中我并不这么用,

使用java文件配置spring xml不方便,编译成class不好改动,虽然可以建立一个properties配置文件,java配置读取properties配置,但是有时xml也是需要改动的,

 所以下面记录下使用spring.xml文件的方法

 

修改MySpringInitializer.class onStartup方法 改成读取spring.xml配置文件的方式

package com.wying.web;

import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * description:编写实现类 实现WebApplicationInitializer
 * 这样tomcat启动时 先执行SpringServletContainerInitializer.class的onStartup方法
 * 在通过HandlesTypes配置 执行该class的onStartup方法
 * date: 2021/3/19
 * author: gaom
 * version: 1.0
 */

public class MySpringInitializer  implements WebApplicationInitializer {
    //spring配置文件也去除的方式
  /*  @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("=========MySpringInitializer onStartup============");
        System.out.println("=========MySpringInitializer 启动spring容器============");
         // 代替 web.xml 中的 listener 初始化
         //<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        AnnotationConfigWebApplicationContext ac_spring = new AnnotationConfigWebApplicationContext();
        // listener中的加载spring.xml的配置文件内容 MySpringXml.class代替 spring.xml
        ac_spring.register(MySpringXml.class);
        //用于初始化spring配置文件 web项目可用可不用

        servletContext.addListener(new ContextLoaderListener(ac_spring));
        System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");
        AnnotationConfigWebApplicationContext ac_mvc = new AnnotationConfigWebApplicationContext();
        //MySpringMvcXml.class代替 spring-mvc.xml
        ac_mvc.register(MySpringMvcXml.class);
        //用于初始化spring配置文件 web项目可用可不用

        //配置spring dispatcherServlet  代替web.xml
        // <servlet-name>springDispatcher</servlet-name>
        //<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ac_mvc);
        //创建前端控制器去名字为dispatcherServlet  <servlet>标签
        ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        //启动顺序设置为1 tomcat启动时就初始化该servlet
        registration.setLoadOnStartup(1);
        //<servlet-mapping>里面的url-patten
        registration.addMapping("*.do");
        System.out.println("=========MySpringInitializer onStartup 运行完毕============");

    }*/

    //读取spring.xml 配置文件的方式
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("保留spring.xml方式=========MySpringInitializer onStartup============");
        System.out.println("=========MySpringInitializer 启动spring容器============");
        servletContext.setInitParameter("contextConfigLocation","classpath:spring.xml");
        //springMVC的servlet
         //添加监听
        servletContext.addListener(new ContextLoaderListener());

        System.out.println("=========MySpringInitializer 配置srping  dispatcherServlet============");
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet());
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("*.do");
        dispatcher.setInitParameter("contextConfigLocation","classpath:spring-mvc.xml");

        System.out.println("=========MySpringInitializer onStartup 运行完毕============");

    }
}

 

spring.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.wying"/>



</beans>

spring-mvc.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.wying"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/views/"></property>
         <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

启动项目

启动成功,并打印出读取spring.xml的方式

测试效果

和java文件代替xml效果一样,完成

 

项目源码已上传github,需要的同学可以下载

 https://github.com/gaomeng6319/JavaSpringWebNoWebxmlDemo

 

springbooy使用shardingsphere_driud报错日子如下 Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-08-11 10:31:45 - Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfiguration': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/tomcat/dbcp/dbcp2/BasicDataSource at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:409) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1341) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1181) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207) at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:229) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:723) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:755) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:402) at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1247) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1236) at com.ahcoder.taskone.TaskOneApplication.main(TaskOneApplication.java:29) Caused by: java.lang.NoClassDefFoundError: org/apache/tomcat/dbcp/dbcp2/BasicDataSource at org.apache.shardingsphere.infra.datasource.pool.metadata.type.dbcp.TomcatDBCPDataSourcePoolMetaData.getType(TomcatDBCPDataSourcePoolMetaData.java:67) at org.apache.shardingsphere.spi.typed.TypedSPIRegistry.lambda$findRegisteredService$0(TypedSPIRegistry.java:44) at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174) at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1359) at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126) at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464) at org.apache.shardingsphere.spi.typed.TypedSPIRegistry.findRegisteredService(TypedSPIRegistry.java:44) at org.apache.shardingsphere.infra.datasource.pool.metadata.DataSourcePoolMetaDataFactory.newInstance(DataSourcePoolMetaDataFactory.java:46) at org.apache.shardingsphere.infra.datasource.props.DataSourceProperties.<init>(DataSourceProperties.java:53) at org.apache.shardingsphere.spring.boot.datasource.DataSourceMapSetter.getDataSource(DataSourceMapSetter.java:92) at org.apache.shardingsphere.spring.boot.datasource.DataSourceMapSetter.getDataSourceMap(DataSourceMapSetter.java:65) at org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfiguration.setEnvironment(ShardingSphereAutoConfiguration.java:122) at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:108) at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:100) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:415) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1791) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ... 25 common frames omitted Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource at java.net.URLClassLoader.findClass(URLClassLoader.java:382) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 47 common frames omitted yml配置文件如下 spring: application: name: task-one # ShardingSphere配置 shardingsphere: mode: type: Standalone # 单机模式 datasource: names: ds-base,ds-2023,ds-2024 default-data-source-name: ds-base # 默认数据源 ds-base: data-source-class-name: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/practice?useSSL=false&serverTimezone=UTC username: root password: 123456 ds-2023: data-source-class-name: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/crm_2023?useSSL=false&serverTimezone=UTC username: root password: 123456 ds-2024: data-source-class-name: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/crm_2024?useSSL=false&serverTimezone=UTC username: root password: 123456 # 分片规则配置 rules: sharding: # 配置分表 tables: # 表名(逻辑表) product_history: # 实际数据节点,格式:数据源名.表名(多个用逗号分隔,这里使用表达式表示多个) actual-data-nodes: ds-$->{2023..2024}.product_history_$->{1..12} # 分库策略 database-strategy: standard: sharding-column: id sharding-algorithm-name: database-inline # 分表策略 table-strategy: standard: sharding-column: id sharding-algorithm-name: table-inline # 分布式主键生成策略 key-generate-strategy: column: id key-generator-name: snowflake # 分片算法配置 sharding-algorithms: database-inline: type: INLINE props: algorithm-expression: ds-$->{id % 3} # 分库规则:按user_id取模,分到3个库 table-inline: type: INLINE props: algorithm-expression: product_history_$->{id % 2} # 分表规则:按user_id取模,分到2个表 # 分布式序列算法配置(雪花算法) key-generators: snowflake: type: SNOWFLAKE props: worker-id: 123 # 其他属性 props: sql-show: true # 打印SQL pom文件如下 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.8</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId> <version>5.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
最新发布
08-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值