precondition

SpringBoot integrates with the MyBatis framework

Add the dependent

< the dependency > < groupId > com. Alibaba < / groupId > < artifactId > druid - spring - the boot - starter < / artifactId > < version > 1.1.10 < / version >  </dependency>Copy the code

Add the configuration

  • application.yml
# Tomcat server: port: 8088 # DataSource spring: datasource: name: druidDataSource type: com.alibaba.druid.pool.DruidDataSource druid: driverClassName: com.mysql.cj.jdbc.Driver url: JDBC: mysql: / / 127.0.0.1:3306 / tmall? useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8 username: root password: 123456 filters: stat,wall,log4j,config max-active: 100 initial-size: 1 max-wait: 60000 min-idle: 1 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: select 'x' test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: true max-open-prepared-statements: 50 max-pool-prepared-statement-per-connection-size: 20Copy the code
  • DruidDataSourceProperties.java
package com.gold.tmall.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author zhang.fuiqng * @date 2021-04-24 14:47:00 */ @ConfigurationProperties(prefix = "spring.datasource.druid") Public class DruidDataSourceProperties {/ * * * * mysql Driver class name: com. Mysql. Cj. JDBC. Driver version (mysql 8.0 above) * oracle: oracle.jdbc.driver.OracleDriver */ private String driverClassName; /** * private String url; /** * private String username; /** * database password */ private String password; /** * The number of physical connections established during initialization. Initialization occurs when the display calls the init method, or the first getConnection */ private int initialSize; /** * private int minIdle; /** * private int maxActive = 100; /** * Get the maximum waiting time for a connection, in milliseconds. After maxWait is configured, fair locks are enabled by default, which reduces concurrency efficiency. * If necessary, you can set useUnfairLock to true to use unfair locks. */ private long maxWait; / * * * has two meanings: * 1) Destroy thread will detect the connection time interval, if the connection is idle time is greater than or equal to minEvictableIdleTimeMillis close physical connection. * 2) testWhileIdle judgment, detailed see testWhileIdle attribute description * / private long timeBetweenEvictionRunsMillis; / * * * connections remain idle instead of expulsion of minimum time * / private long minEvictableIdleTimeMillis; Select * from 'x' where 'x' = 'x'; TestOnBorrow, testOnReturn, and testWhileIdle will not work if validationQuery is null. */ private String validationQuery; /** * You are advised to set this parameter to true to ensure performance and security. * application connection testing, if free time is more than timeBetweenEvictionRunsMillis, performing validationQuery test connection is valid. */ private boolean testWhileIdle; /** * Execute validationQuery when applying for a connection to check whether the connection is valid. This configuration reduces performance. */ private boolean testOnBorrow; /** * Execute validationQuery to check if the connection is valid when the connection is returned. This configuration degrades performance. */ private boolean testOnReturn; /** * Whether to cache preparedStatement, i.e. PSCache. PSCache provides a huge performance boost for databases that support cursors, such as Oracle. You are advised to disable this function in mysql. */ private boolean poolPreparedStatements; /** * To enable PSCache, the configuration must be greater than 0, when greater than 0, poolPreparedStatements automatically trigger change to true. * in the Druid, not Oracle PSCache under too much memory problems, you can put this value configuration, such as 100 * / private int maxPoolPreparedStatementPerConnectionSize; /** * The attribute type is a string, using the alias to configure the extension. * Filter :stat * filter:log4j * Filter :wall */ private String filters; public int getInitialSize() { return initialSize; } public void setInitialSize(int initialSize) { this.initialSize = initialSize; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } public long getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public int getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}Copy the code
  • DruidConfig.java
package com.gold.tmall.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.sql.DataSource; import java.sql.SQLException; / * * * EnableConfigurationProperties ({DruidDataSourceProperties. Class}) is used to step on the import * @ author DruidDataSourceProperties configuration information zhang.fuiqng * @date 2021-04-24 14:59:00 */ @Configuration @EnableConfigurationProperties({DruidDataSourceProperties.class}) public class DruidConfig { @Resource private DruidDataSourceProperties properties; @Bean @ConditionalOnMissingBean public DataSource druidDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(properties.getDriverClassName()); druidDataSource.setUrl(properties.getUrl()); druidDataSource.setUsername(properties.getUsername()); druidDataSource.setPassword(properties.getPassword()); druidDataSource.setInitialSize(properties.getInitialSize()); druidDataSource.setMinIdle(properties.getMinIdle()); druidDataSource.setMaxActive(properties.getMaxActive()); druidDataSource.setMaxWait(properties.getMaxWait()); druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); druidDataSource.setValidationQuery(properties.getValidationQuery()); druidDataSource.setTestWhileIdle(properties.isTestWhileIdle()); druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); druidDataSource.setTestOnReturn(properties.isTestOnReturn()); druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());  try { druidDataSource.setFilters(properties.getFilters()); druidDataSource.init(); } catch (SQLException e) { e.printStackTrace(); } return druidDataSource; } /** * Register Servlet information, Configuration monitoring view * Public ServletRegistrationBean druidServlet() is equivalent to Web Servlet configuration * @return Servlet registration information */ @bean @ConditionalOnMissingBean public ServletRegistrationBean<Servlet> druidServlet() { ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); / / white list servletRegistrationBean. AddInitParameter (" allow ", "127.0.0.1"); // IP blacklist (deny takes precedence over allow if common) : "Deny" :Sorry, You are not permitted to view this page. ServletRegistrationBean. AddInitParameter (" deny ", "127.0.0.1"); / / login to check the information of account password, login to Druid monitoring backstage servletRegistrationBean. AddInitParameter (" loginUsername ", "admin"); servletRegistrationBean.addInitParameter("loginPassword", "admin"); / / whether to reset the data servletRegistrationBean addInitParameter (" resetEnable ", "true"); return servletRegistrationBean; } /** * Register Filter information, Monitor interceptor * Public FilterRegistrationBean FilterRegistrationBean () is equivalent to the Web Filter configuration * @return Filter registration information */ @bean @ConditionalOnMissingBean public FilterRegistrationBean<Filter> filterRegistrationBean() { FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }}Copy the code

Start the problem

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mybatisConfig': Unsatisfied dependency expressed through field 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'druidDataSource' defined in class path resource [com/louis/kitty/boot/config/DruidConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'druidDataSource' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/log4j/Priority at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autowired AnnotationBeanPostProcessor. Java: 586) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~ [spring beans - 5.0.8. RELEASE. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnn OtationBeanPostProcessor. Java: 372) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFac Tory. Java: 1341) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFac Tory. Java: 572) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFacto Ry. Java: 495) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~ [spring beans - 5.0.8. RELEASE. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:22 (2) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~ [spring beans - 5.0.8. RELEASE. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~ [spring beans - 5.0.8. RELEASE. The jar: 5.0.8. RELEASE] the at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory .java: 759) ~ [spring - beans - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContex T.j ava: 869) ~ [spring - the context - 5.0.8. The jar: 5.0.8. RELEASE] the at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~ [spring - the context - 5.0.8. RELEASE. The jar: 5.0.8. RELEASE] the at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationConte Xt. Java: 140) ~ [spring - the boot - 2.0.4. The jar: 2.0.4. RELEASE] the at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring - the boot - 2.0.4. RELEASE. The jar: 2.0.4. RELEASE] the at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring - the boot - 2.0.4. RELEASE. The jar: 2.0.4. RELEASE] the at Org. Springframework. Boot. SpringApplication. Run (SpringApplication. Java: 330) [spring - the boot - 2.0.4. The jar: 2.0.4. RELEASE]  at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring - the boot - 2.0.4. RELEASE. The jar: 2.0.4. RELEASE] the at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring - the boot - 2.0.4. RELEASE. The jar: 2.0.4. RELEASE] at com. Louis. Kitty. Boot. KittyApplication. Main (10) KittyApplication. Java: / classes / : na... Caused by: java.lang.ClassNotFoundException: Org, apache log4j. Priority at java.net.URLClassLoader.findClass (URLClassLoader. Java: 381) ~ [na: 1.8.0 comes with _131] the at Java. Lang. This. LoadClass (424). This Java: ~ [na: 1.8.0 comes with _131] the at Sun. Misc. The Launcher $AppClassLoader. LoadClass (335). The Launcher Java: ~ [na: 1.8.0 comes with _131] the at Java. Lang. This. LoadClass (357). This Java: ~ [na: 1.8.0 comes with _131]... 49 common frames omittedCopy the code
  • Add the dependent
<! Log4j --> <dependency> <groupId>log4j</groupId> <artifactId> <version>1.2.17</version> </dependency>Copy the code
  • Configure log4j

Add the log4j.properties file under the SRC /main/resources path

### set log levels ###
log4j.rootLogger = INFO, console, infoFile, errorFile
LocationInfo=true

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m   %x %n

log4j.appender.infoFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.infoFile.Threshold = INFO
log4j.appender.infoFile.File = D:/logs/log
log4j.appender.infoFile.DatePattern = '.'yyyy-MM-dd'.log'
log4j.appender.infoFile.Append=true
log4j.appender.infoFile.layout = org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n

log4j.appender.errorFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorFile.Threshold = ERROR
log4j.appender.errorFile.File = D:/logs/error
log4j.appender.errorFile.DatePattern = '.'yyyy-MM-dd'.log'
log4j.appender.errorFile.Append=true
log4j.appender.errorFile.layout = org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n

#log4j.appender.debugfile = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.debugfile.Threshold = DEBUG
#log4j.appender.debugfile.File = D:/logs/debug
#log4j.appender.debugfile.DatePattern = '.'yyyy-MM-dd'.log'
#log4j.appender.debugfile.Append=true
#log4j.appender.debugfile.layout = org.apache.log4j.PatternLayout
#log4j.appender.debugfile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n
Copy the code

Check the monitor

Download the source code

Gitee.com/zhang_fuqin…