Install Mybatis Druid
Add the dependent
<! --druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> The < version > 1.1.16 < / version > < / dependency > <! --mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.3.2 < / version > < / dependency > <! --mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> Slf4j <dependency> <groupId>org.springframework.boot</groupId> slf4J <dependency> <groupId> < artifactId > spring - the boot - starter - log4j < / artifactId > < version > 1.3.8. RELEASE < / version > < / dependency > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <! > <exclusions> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency>Copy the code
Attach the log4j.properties configuration
Log4j. rootLogger=INFO, file, console 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 {MM yyyy - HH: MM: ss} % 5 p % c {1} : % L - % m % n # log file log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.file=logs/springboot.log log4j.appender.file.DatePattern='.'yyyy-MM-dd log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM HH:mm:ss} %5p %c{1}:%L - %m%nCopy the code
2. Create a Controller, DAO, and Service in advance for database query and test
dao
import com.ljy.sys.entity.User;
import java.util.List;
public interface SysUserMapper {
List<User> findAll();
}
Copy the code
Mapper
Service and its implementation classes
import com.ljy.sys.entity.User;
import java.util.List;
public interface SysUserService {
List<User> findAll();
}
Copy the code
import com.ljy.sys.dao.SysUserMapper; import com.ljy.sys.entity.User; import com.ljy.sys.model.SysUserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @author ljy&jcq */ @service public class SysUserServiceImpl implements SysUserService { @Resource private SysUserMapper sysUserMapper; @Override public List<User> findAll() { return sysUserMapper.findAll(); }}Copy the code
controller
import com.ljy.sys.model.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("user") public class SysUserController { @Autowired private SysUserService sysUserService; @GetMapping("/findAll") public Object findAll(){ return sysUserService.findAll(); }}Copy the code
Write Mybatis configuration class
import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.sql.DataSource; /** * mybatis config class * @author ljy&jcQ * MapperScan scan DAO ** / @configuration @mapperscan ("com.ljy.sys.**.dao") public class MybatisConfig { @Autowired private DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception{ SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); / / scanning service layer sqlSessionFactoryBean. SetTypeAliasesPackage (" com. Ljy. Sys. * *. The model "); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); / / scanning mapping file Mapper's address sqlSessionFactoryBean. SetMapperLocations (resolver. GetResources (" classpath * : / templates / *. XML ")); return sqlSessionFactoryBean.getObject(); }}Copy the code
Modifying the startup class
// Indicates that the com.ljy.sys package is automatically scanned when the application is started. Of course, Spring Boot also automatically scans the startup class package and its subpackages. @springBootApplication (scanBasePackages = {"com.ljy.sys"}) public class SysApplication {public static void main(String[] args) { SpringApplication.run(SysApplication.class, args); }}Copy the code
Write application.yml to configure druid’s properties
Spring: a datasource: # database connection configuration type: com. Alibaba. Druid. Pool. DruidDataSource driver - class - name: Com. Mysql. Cj, JDBC Driver url: JDBC: mysql: / / 127.0.0.1:3306 / salery? ServerTimezone =GMT%2B8&characterEncoding=UTF-8 Username: root password: root # Initial-size: 5 # Initial-size min-idle: 5 # Max max-active: 100 # Max max-wait: 60000 # connection timeout time-between-eviction-runs-millis: 60000 # Configure the interval for detecting idle connections to be closed, in milliseconds min-evictable-idle-time-millis: ValidationQuery: selectVersion () test-while-idle: selectVersion () Test-on-borrow: false # Test-on-return: false # Test connection filters when the connection is returned to the connection pool: Log4j adds poolPreparedStatements to the database where log4j uses the same type of log4j system: true maxPoolPreparedStatementPerConnectionSize: 20 maxOpenPreparedStatements: 20 connectionProperties: druid.stat.slowSqlMillis=200; druid.stat.logSlowSql=trueCopy the code
Writing configuration classes
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; 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 org.springframework.context.annotation.Primary; import javax.sql.DataSource; @author jcq&ljy */ @configuration public class DruidConfig {@bean (name = "dataSource") // We need to automatically inject the spring.datasource properties. Add @configurationProperties (prefix = "spring.datasource. Druid ") to the class name to import the data set in YML / / in this configuration class add @ EnableConfigurationProperties ({custom. Class}) import custom configuration in this method, manually set into reference annotation methods @ConfigurationProperties("spring.datasource") @Primary public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); DruidDataSource() {druidDataSource DataSource = new druidDataSource(); * datasource.setUrl(properties.getUrl()); * datasource.setUsername(properties.getUsername()); * datasource.setPassword(properties.getPassword()); * datasource.setDriverClassName(properties.getDriverClassName()); * datasource.setInitialSize(properties.getInitialSize()); * datasource.setMinIdle(properties.getMinIdle()); * datasource.setMaxActive(properties.getMaxActive()); * datasource.setMaxWait(properties.getMaxWait()); * datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); * datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); * datasource.setValidationQuery(properties.getValidationQuery()); * datasource.setTestWhileIdle(properties.isTestWhileIdle()); * datasource.setTestOnBorrow(properties.isTestOnBorrow()); * datasource.setTestOnReturn(properties.isTestOnReturn()); * properties.setPoolPreparedStatements(properties.isPoolPreparedStatements()); * properties.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize()); * properties.setFilters(properties.getFilters()); * return datasource; */ ** /** / A Servlet * @return */ @bean public ServletRegistrationBean druidServlet() {// Specify that the interceptor intercepts only requests from the Druid admin page ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); / / IP white list, if not set or is empty, allowing all access. (can't write *, or complains) servletRegistrationBean. AddInitParameter (" allow ", ""); / / IP blacklist (common existence, deny in preference to allow) servletRegistrationBean. AddInitParameter (" deny ", "192.168.1.19"); / / console management user name and password servletRegistrationBean addInitParameter (" loginUsername ", "admin"); servletRegistrationBean.addInitParameter("loginPassword", "admin"); / / if we can Reset the data disabled HTML on the page "Reset All" function servletRegistrationBean. AddInitParameter (" resetEnable ", "false"); return servletRegistrationBean; } /** * Configure a web monitoring filter * @return */ @bean public FilterRegistrationBean FilterRegistrationBean () { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }}Copy the code
The loginhttp://localhost:8080/druid/login.html
Enter the account password set in the configuration class, you can see the following interface:
But opening the data source shows the following:
Don’t worry, you only need to send a request to the controller we wrote just now. After sending the request, the result is as follows:
Particular attention should be paid to:
If this line is empty, you need to check whether the listener configuration or logging system matches the configuration in YML.
If spring monitoring is empty, it is because we have not set the aspect, and we need to set the aspect
Write spring monitor facets
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor; import org.springframework.aop.Advisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.JdkRegexpMethodPointcut; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @author jcq&ljy */ @configuration public class SpringDaoMethodAspect {@bean public DruidStatInterceptor druidStatInterceptor(){ return new DruidStatInterceptor(); } @Bean public JdkRegexpMethodPointcut druidStatPointcut(){ JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut(); String patterns = "com.ljy.*.*.service.*"; String patterns2 = "com.ljy.*.*.dao.*"; druidStatPointcut.setPatterns(patterns,patterns2); return druidStatPointcut; } @Bean public Advisor druidStatAdvisor() { return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor()); }}Copy the code
Note: If it is still null, first check whether aop dependencies are imported
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code
Finally, the successful screenshot is attached
The last
After reading, you can leave a message in the comment area. If you feel helpful, you can give me a thumbs-up!