Получение ошибки Рассмотрите возможность определения bean-компонента типа 'org.springframework.jdb c .core.JdbcTemplate' в вашей конфигурации. - PullRequest
0 голосов
/ 30 января 2020

Я получаю сообщение об ошибке при запуске приложения весенней загрузки.

2020-01-30 10:33:19.294  WARN 11168 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mailManagerService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userRepository': Unsatisfied dependency expressed through field 'jdbcTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2020-01-30 10:33:19.294  INFO 11168 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-01-30 10:33:19.309  INFO 11168 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-01-30 10:33:19.434 ERROR 11168 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Описание:

Поле jdbcTemplate в com.service.el.microservice.user.UserRepository требуется компонент типа org.springframework.jdbc.core.JdbcTemplate, который не может быть найденным.

Точка внедрения имеет следующие аннотации: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Действие:

Рассмотрите возможность определения bean-компонента типа org.springframework.jdbc.core.JdbcTemplate в вашей конфигурации.

Но проблема в том, что я уже определил @ Bean для JdbcTemplate в конфигурации. Я использую java 1.8, подпружиненный загрузчик: 2.2.4

Может кто-нибудь помочь мне избавиться от этой проблемы?



@Configuration
@Component
public class someclass {

    @Bean
    public DataSource getDatasource() {
        DriverManagerDataSource datasource = new DriverManagerDataSource();
        datasource.setDriverClassName(this.dbDriver);
        datasource.setUrl(this.dbURL);
        datasource.setUsername(this.dbUserName);
        datasource.setPassword(this.dbPassword);
        return datasource;
    }

    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
        //return jdbcTemplate;
    }

    @Bean
    public ResourceBundle getQueryResourceBundle() {
        ResourceBundle rb = ResourceBundle.getBundle("query");
        return rb;
    }
}

Это класс, где JDBCtemplate был б

@Repository
public class AutoEventRepository {

    @Autowired JdbcTemplate jdbcTemplate;
    @Autowired ResourceBundle resourceBundle;
    private static final Logger log = LoggerFactory.getLogger(AutoEventRepository.class);

    public List<AutoEventVO> getExistPielData(String esn) {
        try{
            List<AutoEventVO> List = jdbcTemplate.query(resourceBundle.getString(AutoEventQueryConstant.GET_EXIST_PIEL_DATA),
            new Object[] { esn }, new existPIELMapper());
            return List;
        }

Ответы [ 2 ]

0 голосов
/ 30 января 2020
@Configuration
@ComponentScan(basePackages = "my.base.package")
public class RootConfig {
    ... other configuration ...
}

Вы можете go опередить и удалить аннотацию @component для SomeClass, поскольку @configuration содержит @component внутри, как в Spring DOCS: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html

Вы можете go и удалите компонент JDBCTemplate из SomeClass и попробуйте что-то вроде этого:
@ Repository

public class AutoEventRepository {

   JdbcTemplate jdbcTemplate;   
        @Autowired 
       public AutoEventRepository (DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
0 голосов
/ 30 января 2020

Класс, содержащий метод

@ Bean JdbcTemplate

, должен иметь

@ Конфигурация

аннотация, чтобы во время сканирования компонентов пружина могла создать бин JdbcTemplate.

Измените код с помощью приведенного ниже фрагмента и повторите попытку.

@Configuration
public class SomeClass {

    @Bean
    public DataSource getDatasource() {
        DriverManagerDataSource datasource = new DriverManagerDataSource();
        datasource.setDriverClassName(this.dbDriver);
        datasource.setUrl(this.dbURL);
        datasource.setUsername(this.dbUserName);
        datasource.setPassword(this.dbPassword);
        return datasource;
    }

    @Bean("jdbcTemplate")
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean("resourceBundle")
    public ResourceBundle resourceBundle() {
        ResourceBundle rb = ResourceBundle.getBundle("query");
        return rb;
    }
}
...