您的位置:首页技术文章
文章详情页

java - 使用Spring Boot配置Druid时dataSource无法被autowired

【字号: 日期:2023-11-10 17:15:36浏览:19作者:猪猪

问题描述

配置好了dataSource之后,想测试一下有没有配置成功

package com.yang.Controller;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * Created by Yang on 2017/6/6. */@RestControllerpublic class TestController { @Autowired private DruidDataSource dataSource; @RequestMapping('/hello') public String index() {String sql = 'select * from reader;';String str = '';PreparedStatement ps = null;ResultSet rs = null;try { ps = dataSource.getConnection().prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()){str = rs.getString(2); }} catch (SQLException e) { e.printStackTrace();}return str; }}

这个TestController是可以跑成功的,我想把dataSource.getConnection()再封装一下

package com.yang.Utils;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.pool.DruidPooledConnection;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.sql.SQLException;/** * Created by Yang on 2017/6/6. */public class ConnectionManager { private Logger logger = LoggerFactory.getLogger(ConnectionManager.class); @Autowired private DruidDataSource dataSource; private static volatile ConnectionManager connectionManager; private ConnectionManager(){} public static ConnectionManager getInstance(){if(connectionManager == null){ synchronized (ConnectionManager.class){if(connectionManager == null){ connectionManager = new ConnectionManager();} }}return connectionManager; } public DruidPooledConnection getConn(){DruidPooledConnection conn = null;try { conn = dataSource.getConnection();} catch (SQLException e) { logger.error('get connection error,the connection is null', e); e.printStackTrace();}return conn; }}

写了这个ConnectionManager,但是在这个类里面,dataSource是null,不知道怎么回事,想请教一下大家。另外还有一个问题,在使用Spring Boot的时候,如何进行单元测试,我开始用单元测试测试一个ConnectionManager,但是一直不成功

D:Javajdk_8u92binjava -Dspring.output.ansi.enabled=always -Didea.launcher.port=7532 '-Didea.launcher.bin.path=D:developideaIntelliJ IDEA 2016.2.5bin' -Dfile.encoding=UTF-8 -classpath 'D:environmentJavajdk_8u92jrelibcharsets.jar;D:environmentJavajdk_8u92jrelibdeploy.jar;D:environmentJavajdk_8u92jrelibextaccess-bridge-64.jar;D:environmentJavajdk_8u92jrelibextcldrdata.jar;D:environmentJavajdk_8u92jrelibextdnsns.jar;D:environmentJavajdk_8u92jrelibextjaccess.jar;D:environmentJavajdk_8u92jrelibextjfxrt.jar;D:environmentJavajdk_8u92jrelibextlocaledata.jar;D:environmentJavajdk_8u92jrelibextnashorn.jar;D:environmentJavajdk_8u92jrelibextsunec.jar;D:environmentJavajdk_8u92jrelibextsunjce_provider.jar;D:environmentJavajdk_8u92jrelibextsunmscapi.jar;D:environmentJavajdk_8u92jrelibextsunpkcs11.jar;D:environmentJavajdk_8u92jrelibextzipfs.jar;D:environmentJavajdk_8u92jrelibjavaws.jar;D:environmentJavajdk_8u92jrelibjce.jar;D:environmentJavajdk_8u92jrelibjfr.jar;D:environmentJavajdk_8u92jrelibjfxswt.jar;D:environmentJavajdk_8u92jrelibjsse.jar;D:environmentJavajdk_8u92jrelibmanagement-agent.jar;D:environmentJavajdk_8u92jrelibplugin.jar;D:environmentJavajdk_8u92jrelibresources.jar;D:environmentJavajdk_8u92jrelibrt.jar;E:myJavaLibraryManagertargetclasses;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-starter1.4.1.RELEASEspring-boot-starter-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot1.4.1.RELEASEspring-boot-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-core4.3.3.RELEASEspring-core-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-context4.3.3.RELEASEspring-context-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-aop4.3.3.RELEASEspring-aop-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-beans4.3.3.RELEASEspring-beans-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-expression4.3.3.RELEASEspring-expression-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-autoconfigure1.4.1.RELEASEspring-boot-autoconfigure-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-starter-logging1.4.1.RELEASEspring-boot-starter-logging-1.4.1.RELEASE.jar;D:environmentmavenrepositorychqoslogbacklogback-classic1.1.7logback-classic-1.1.7.jar;D:environmentmavenrepositorychqoslogbacklogback-core1.1.7logback-core-1.1.7.jar;D:environmentmavenrepositoryorgslf4jslf4j-api1.7.21slf4j-api-1.7.21.jar;D:environmentmavenrepositoryorgslf4jjcl-over-slf4j1.7.21jcl-over-slf4j-1.7.21.jar;D:environmentmavenrepositoryorgslf4jjul-to-slf4j1.7.21jul-to-slf4j-1.7.21.jar;D:environmentmavenrepositoryorgslf4jlog4j-over-slf4j1.7.21log4j-over-slf4j-1.7.21.jar;D:environmentmavenrepositoryorgyamlsnakeyaml1.17snakeyaml-1.17.jar;D:environmentmavenrepositoryjunitjunit4.10junit-4.10.jar;D:environmentmavenrepositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-starter-web1.4.1.RELEASEspring-boot-starter-web-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-starter-tomcat1.4.1.RELEASEspring-boot-starter-tomcat-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgapachetomcatembedtomcat-embed-core8.5.5tomcat-embed-core-8.5.5.jar;D:environmentmavenrepositoryorgapachetomcatembedtomcat-embed-el8.5.5tomcat-embed-el-8.5.5.jar;D:environmentmavenrepositoryorgapachetomcatembedtomcat-embed-websocket8.5.5tomcat-embed-websocket-8.5.5.jar;D:environmentmavenrepositoryorghibernatehibernate-validator5.2.4.Finalhibernate-validator-5.2.4.Final.jar;D:environmentmavenrepositoryjavaxvalidationvalidation-api1.1.0.Finalvalidation-api-1.1.0.Final.jar;D:environmentmavenrepositoryorgjbossloggingjboss-logging3.3.0.Finaljboss-logging-3.3.0.Final.jar;D:environmentmavenrepositorycomfasterxmlclassmate1.3.1classmate-1.3.1.jar;D:environmentmavenrepositorycomfasterxmljacksoncorejackson-databind2.8.3jackson-databind-2.8.3.jar;D:environmentmavenrepositorycomfasterxmljacksoncorejackson-annotations2.8.3jackson-annotations-2.8.3.jar;D:environmentmavenrepositorycomfasterxmljacksoncorejackson-core2.8.3jackson-core-2.8.3.jar;D:environmentmavenrepositoryorgspringframeworkspring-web4.3.3.RELEASEspring-web-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-webmvc4.3.3.RELEASEspring-webmvc-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgmybatisspringbootmybatis-spring-boot-starter1.1.1mybatis-spring-boot-starter-1.1.1.jar;D:environmentmavenrepositoryorgmybatisspringbootmybatis-spring-boot-autoconfigure1.1.1mybatis-spring-boot-autoconfigure-1.1.1.jar;D:environmentmavenrepositoryorgmybatismybatis3.4.0mybatis-3.4.0.jar;D:environmentmavenrepositoryorgmybatismybatis-spring1.3.0mybatis-spring-1.3.0.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-starter-jdbc1.4.1.RELEASEspring-boot-starter-jdbc-1.4.1.RELEASE.jar;D:environmentmavenrepositoryorgapachetomcattomcat-jdbc8.5.5tomcat-jdbc-8.5.5.jar;D:environmentmavenrepositoryorgapachetomcattomcat-juli8.5.5tomcat-juli-8.5.5.jar;D:environmentmavenrepositoryorgspringframeworkspring-jdbc4.3.3.RELEASEspring-jdbc-4.3.3.RELEASE.jar;D:environmentmavenrepositoryorgspringframeworkspring-tx4.3.3.RELEASEspring-tx-4.3.3.RELEASE.jar;D:environmentmavenrepositorymysqlmysql-connector-java5.1.39mysql-connector-java-5.1.39.jar;D:environmentmavenrepositoryorgspringframeworkbootspring-boot-devtools1.4.1.RELEASEspring-boot-devtools-1.4.1.RELEASE.jar;D:environmentmavenrepositorycomalibabadruid1.0.29druid-1.0.29.jar;D:environmentJavajdk_8u92jre..libjconsole.jar;D:environmentJavajdk_8u92jre..libtools.jar;D:developideaIntelliJ IDEA 2016.2.5libidea_rt.jar' com.intellij.rt.execution.application.AppMain com.yang.Application . ____ _ __ _ _ / / ___’_ __ _ _(_)_ __ __ _ ( ( )___ | ’_ | ’_| | ’_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) ’ |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot ::(v1.4.1.RELEASE)2017-06-06 23:18:44.851 INFO 52496 --- [ restartedMain] com.yang.Application : Starting Application on Yang with PID 52496 (E:myJavaLibraryManagertargetclasses started by Yang in E:myJavaLibraryManager)2017-06-06 23:18:44.856 INFO 52496 --- [ restartedMain] com.yang.Application : No active profile set, falling back to default profiles: default2017-06-06 23:18:45.257 INFO 52496 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@46a9c0: startup date [Tue Jun 06 23:18:45 CST 2017]; root of context hierarchy2017-06-06 23:18:47.356 WARN 52496 --- [ restartedMain] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in ’[com.yang.Mapper]’ package. Please check your configuration.2017-06-06 23:18:47.674 WARN 52496 --- [ restartedMain] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in ’[com.yang]’ package. Please check your configuration.2017-06-06 23:18:48.316 INFO 52496 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean ’org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration’ of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$7d3489f7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)2017-06-06 23:18:49.813 INFO 52496 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2017-06-06 23:18:49.835 INFO 52496 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service Tomcat2017-06-06 23:18:49.837 INFO 52496 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.52017-06-06 23:18:50.072 INFO 52496 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2017-06-06 23:18:50.072 INFO 52496 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4821 ms2017-06-06 23:18:50.448 INFO 52496 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: ’dispatcherServlet’ to [/]2017-06-06 23:18:50.456 INFO 52496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ’characterEncodingFilter’ to: [/*]2017-06-06 23:18:50.457 INFO 52496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ’hiddenHttpMethodFilter’ to: [/*]2017-06-06 23:18:50.457 INFO 52496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ’httpPutFormContentFilter’ to: [/*]2017-06-06 23:18:50.457 INFO 52496 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ’requestContextFilter’ to: [/*]2017-06-06 23:18:50.609 WARN 52496 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ’connectionManager’: Unsatisfied dependency expressed through field ’dataSource’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.alibaba.druid.pool.DruidDataSource]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}2017-06-06 23:18:50.616 INFO 52496 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service Tomcat2017-06-06 23:18:50.650 WARN 52496 --- [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread: java.lang.Object.wait(Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143) com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)2017-06-06 23:18:50.685 INFO 52496 --- [ restartedMain] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with ’debug’ enabled.2017-06-06 23:18:50.984 ERROR 52496 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : ***************************APPLICATION FAILED TO START***************************Description:Field dataSource in com.yang.Utils.ConnectionManager required a bean of type ’com.alibaba.druid.pool.DruidDataSource’ that could not be found.Action:Consider defining a bean of type ’com.alibaba.druid.pool.DruidDataSource’ in your configuration.Process finished with exit code 0

package com.yang.Configuration;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;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 java.sql.SQLException;import java.util.HashMap;import java.util.Map;/** * Created by Yang on 2017/6/6. */@Configuration@EnableAutoConfigurationpublic class DruidDBConfig { private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class); @Value('${spring.datasource.url}') private String dbUrl; @Value('${spring.datasource.username}') private String username; @Value('${spring.datasource.password}') private String password; @Value('${spring.datasource.driverClassName}') private String driverClassName; @Value('${spring.datasource.initialSize}') private int initialSize; @Value('${spring.datasource.minIdle}') private int minIdle; @Value('${spring.datasource.maxActive}') private int maxActive; @Value('${spring.datasource.maxWait}') private int maxWait; @Value('${spring.datasource.timeBetweenEvictionRunsMillis}') private int timeBetweenEvictionRunsMillis; @Value('${spring.datasource.minEvictableIdleTimeMillis}') private int minEvictableIdleTimeMillis; @Value('${spring.datasource.validationQuery}') private String validationQuery; @Value('${spring.datasource.testWhileIdle}') private boolean testWhileIdle; @Value('${spring.datasource.testOnBorrow}') private boolean testOnBorrow; @Value('${spring.datasource.testOnReturn}') private boolean testOnReturn; @Value('${spring.datasource.poolPreparedStatements}') private boolean poolPreparedStatements; @Value('${spring.datasource.maxPoolPreparedStatementPerConnectionSize}') private int maxPoolPreparedStatementPerConnectionSize; @Value('${spring.datasource.filters}') private String filters; @Value('{spring.datasource.connectionProperties}') private String connectionProperties; @Bean //声明其为Bean实例 @Primary //在同样的DataSource中,首先使用被标注的DataSource public DruidDataSource dataSource(){DruidDataSource datasource = new DruidDataSource();datasource.setUrl(this.dbUrl);datasource.setUsername(username);datasource.setPassword(password);datasource.setDriverClassName(driverClassName);//configurationdatasource.setInitialSize(initialSize);datasource.setMinIdle(minIdle);datasource.setMaxActive(maxActive);datasource.setMaxWait(maxWait);datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);datasource.setValidationQuery(validationQuery);datasource.setTestWhileIdle(testWhileIdle);datasource.setTestOnBorrow(testOnBorrow);datasource.setTestOnReturn(testOnReturn);datasource.setPoolPreparedStatements(poolPreparedStatements);datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);try { datasource.setFilters(filters);} catch (SQLException e) { logger.error('druid configuration initialization filter', e);}datasource.setConnectionProperties(connectionProperties);return datasource; } @Bean public ServletRegistrationBean druidServletRegistrationBean() {ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();servletRegistrationBean.setServlet(new StatViewServlet());servletRegistrationBean.addUrlMappings('/druid/*');return servletRegistrationBean; } /** * 注册DruidFilter拦截 * * @return */ @Bean public FilterRegistrationBean duridFilterRegistrationBean() {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();filterRegistrationBean.setFilter(new WebStatFilter());Map<String, String> initParams = new HashMap<String, String>();//设置忽略请求initParams.put('exclusions', '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*');filterRegistrationBean.setInitParameters(initParams);filterRegistrationBean.addUrlPatterns('/*');return filterRegistrationBean; }}

问题解答

回答1:

ConnectionManager 这个类没有@Component声明,spring无法管理这个类,也无法注入dataSource

回答2:

注入错误,前面的是正解,没有Component声明,需要通过配置文件,让Spring管理这个bean,后续才能正确注入。然后测试,可以使用spring-boot-starter-test,里面包含junit,mock,assertJ等,spring-boot的官方文档对于测试又很详细的说明,可以看一下。提供了很多方便的注解,大体上首先要在测试类上加上两个:@RunWith(SpringRunner.class)@SpringBootTest其次还有加载不同配置文件的注解,建议看文档

标签: java
相关文章: