web-dev-qa-db-ja.com

構成でタイプ 'org.springframework.jdbc.core.JdbcTemplate'のBeanを定義することを検討してください

パッケージ名:com.sample

SpringMain.Java

@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();
    }
}

pacakge名:com.sample.infra

SampleClass.Java

@Component
public class SampleClass 
{

    @Autowired
    ThreadSample threadSample;

    public void callThread()
    {
        System.out.println("Inside SampleClass");
        threadSample.start();
    }
}

pacakage名:com.sample.dao

ThreadSample.Java

@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();
    }
}

application.properties

#DB Credentials
spring.datasource.url=jdbc:jtds:sqlserver://1.12.13.14
spring.datasource.username=uname
spring.datasource.password=pwd

pom.xml

<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>

これで、すべてのファイルを1つのパッケージに配置すると、正常に機能します。しかし、機能に応じて配布すると、エラーが発生します。この問題を解決するにはどうすればよいですか。

以下に提案するようにベースパッケージを追加した後、次のようなエラーが発生しました

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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.
5
Tatkal

今日同様の問題が発生し、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:私はMySQLDBを持っていました。適切なドライバクラスとURLを設定する必要があります

2
supreethmurthy

構成の追加

@Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(5);
    executor.setMaxPoolSize(10);
    executor.setQueueCapacity(25);
    return executor;
}
0

以下を追加します。

@ComponentScan(basePackages={"com.sample"})
0
spandey15

削除する

@ComponentScan

またはに変更します

@ComponentScan(basePackage="com.sample")
0
Shanu Gupta