springmvc集成druid
时间: 2023-07-11 22:39:58 浏览: 107
spring,mybatis,springmvc整合
集成Druid需要以下步骤:
1. 首先在pom.xml中添加Druid和MySQL的依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
```
2. 在web.xml中添加Druid的Servlet和Filter:
```xml
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>DruidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DruidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
```
3. 创建Druid的配置类,并添加数据源相关配置:
```java
@Configuration
public class DruidConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Bean
public DataSource druidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
return dataSource;
}
}
```
4. 修改application.properties(或者application.yml)配置文件,添加数据源相关配置:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
5. 在Spring MVC配置文件中添加数据源配置:
```java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example"})
public class MvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource);
}
}
```
这样就完成了Spring MVC集成Druid的配置。可以通过访问`http://localhost:port/druid`来查看Druid的监控页面,并进行相关的数据源监控和管理。
阅读全文