当前位置: 首页 > 知识库问答 >
问题:

考虑在配置中定义一个“org.springframework.jdbc.core.jdbctemplate”类型的bean

施飞雨
2023-03-14

包名:com.sample

@SpringBootApplication
@ComponentScan
public class SpringMain implements CommandLineRunner
{
    @Autowired
    SampleClass sampleClass;

    public static void main(String[] args) {
        SpringApplication.run(SpringMain.class, args);

    }

    @Override
    public void run(String... args) throws Exception 
    {
        sampleClass.callThread();
    }
}
@Component
public class SampleClass 
{

    @Autowired
    ThreadSample threadSample;

    public void callThread()
    {
        System.out.println("Inside SampleClass");
        threadSample.start();
    }
}
@Component
public class ThreadSample extends Thread
{
    @Autowired
    JdbcTemplate jdbcTemplate;

    public void run()
    {
        init();
    }

    public String init()
    {
        System.out.println("Inside ThreadSample");
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate).withProcedureName("sp_procedureName");

        Map<String, Object> initiatorMapData = jdbcCall.execute();

        JSONArray initiatorJSONArray = JSONArray.fromObject(initiatorMapData.get("#result-set-1"));

        System.out.println("GetInitiators JSONArray: "+initiatorJSONArray);

        return initiatorJSONArray.toString();
    }
}
#DB Credentials
spring.datasource.url=jdbc:jtds:sqlserver://1.12.13.14
spring.datasource.username=uname
spring.datasource.password=pwd
<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>springBoot</groupId>
  <artifactId>springBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
        <java.version>1.8</java.version>
    </properties>

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>

    <dependencies>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
         <exclusions>
            <exclusion>
                <artifactId>tomcat-annotations-api</artifactId>
                <groupId>org.apache.tomcat</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-core</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-el</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
            <exclusion>
                <artifactId>tomcat-embed-websocket</artifactId>
                <groupId>org.apache.tomcat.embed</groupId>
            </exclusion>
         </exclusions>
     </dependency>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>


        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
            <version>1.3.1</version>
        </dependency>

<dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

          <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

现在,当我把所有文件放在一个包下时,它工作得很好。但当我根据功能进行分配时,错误就会发生。我该如何解决这个问题。

按照下面的建议添加basepackages后,我收到的错误为

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

2018-04-25 11:37:33.615  INFO 11552 --- [           main] com.sample.SpringMain                    : Starting SpringMain on Computer with PID 11552 (D:\SpringExample\springBoot\target\classes started by User in D:\SpringExample\springBoot)
2018-04-25 11:37:33.617  INFO 11552 --- [           main] com.sample.SpringMain                    : No active profile set, falling back to default profiles: default
2018-04-25 11:37:33.655  INFO 11552 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f490758: startup date [Wed Apr 25 11:37:33 IST 2018]; root of context hierarchy
2018-04-25 11:37:34.370  WARN 11552 --- [           main] o.h.v.m.ParameterMessageInterpolator     : HV000184: ParameterMessageInterpolator has been chosen, EL interpolation will not be supported
2018-04-25 11:37:34.559  WARN 11552 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'asynchronousService': Unsatisfied dependency expressed through field 'taskExecutor'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.task.TaskExecutor' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-04-25 11:37:34.564  INFO 11552 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-04-25 11:37:34.626 ERROR 11552 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field taskExecutor in com.sample.dao.AsynchronousService required a bean of type 'org.springframework.core.task.TaskExecutor' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.core.task.TaskExecutor' in your configuration.

共有1个答案

夏侯智鑫
2023-03-14

我今天遇到了一个类似的问题,我创建了一个DatabaseConfig类来解决这个问题

@Configuration
   public class DatabaseConfig {
      @Bean
      public DataSource dataSource(){
         DriverManagerDataSource dataSource = new DriverManagerDataSource();
         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
         dataSource.setUrl("jdbc:mysql://localhost:3306/myDB");
         dataSource.setUsername( "root" );
         dataSource.setPassword( "" );
         return dataSource;
      }
   }

PS:我有一个MySQL数据库。您需要设置正确的驱动程序类和url

 类似资料: