Это может показаться явной ошибкой, но я не могу ее найти. Ниже мой код и конфигурации:@Autowired не работает для JdbcTemplate, когда DAO имеет @Repository
Класс Application
@SpringBootApplication
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
SQL Config класса
@Configuration
public class PostgreSQLConfig {
@Bean
public DataSource getDBDataSource() {
final DriverManagerDataSource driverManagerDataSource
= new DriverManagerDataSource(
"jdbc:postgresql://localhost:5432/applicationdb",
"username",
"password"
);
driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
return driverManagerDataSource;
}
@Bean
public JdbcTemplate getJdbcTemplate(final DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
@Repository DAO КЛАСС
@Repository
public class CustomDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
.
.
@Component DAO класса
@Component
public class AnotherDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
.
.
Объект JdbcTemplate
заселяется за @Component
аннотированный класс. Но объект имеет значение null для @Repository
аннотированного класса. Я начал весеннюю загрузку с регистрацией, установленной в DEBUG, и не смог найти никакой ошибки при создании JdbcTemplate
bean. Из журналов я могу сделать вывод, что метод вызывается, и компонент создается. JdbcTemplate
также имеет ссылку на DataSource
.
Если аннотация @Repository
изменена на @Component
, код работает нормально.
- При использовании пружины JDBC, мы можем аннотировать класс DAO с
@Repository
? - Почему инъекция зависимостей работает с
@Component
, но не для@Repository
?
Согласно предложению М. Дейна, я внесла следующие изменения.
- Удален
PostgreSQLConfig
класса - Добавлен
application.properties
файлового
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/applicationdb
spring.datasource.user=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
Свойства загружаются яровым приложением. Ниже приведены сообщения журнала:
2017-01-06 15:03:02 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.datasource.driver-class-name' in [applicationConfigurationProperties] with type [String]
2017-01-06 15:03:02 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.datasource.password' in [applicationConfigurationProperties] with type [String]
2017-01-06 15:03:02 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.datasource.user' in [applicationConfigurationProperties] with type [String]
2017-01-06 15:03:02 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'spring.datasource.url' in [applicationConfigurationProperties] with type [String]
Получалось исключение. Ниже приведены детали:
2017-01-06 15:03:05 [main] DEBUG o.s.b.d.LoggingFailureAnalysisReporter - Application failed to start due to an exception
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)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
классы DAO отмечены @Repository
аннотацию.
build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE'
}
}
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'application'
apply plugin: 'org.springframework.boot'
def applicationVersion = '0.0.1-SNAPSHOT'
def dependencyVersions = [
slf4j: '1.7.22',
logback: '1.1.8',
postgresql: '9.4.1212',
junit: '4.12'
]
group = 'com.appl'
version = applicationVersion
mainClassName = 'com.appl.Application'
war {
baseName = 'my-custom-appl'
version = applicationVersion
}
war.dependsOn test
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
configurations.all {
exclude group: 'commons-logging', module: 'commons-logging'
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-jdbc'
compile 'org.springframework:spring-jdbc'
compile "org.slf4j:jcl-over-slf4j:${dependencyVersions.slf4j}"
compile "org.postgresql:postgresql:${dependencyVersions.postgresql}"
compile "ch.qos.logback:logback-classic:${dependencyVersions.logback}"
testCompile "junit:junit:${dependencyVersions.junit}"
testCompile 'org.springframework.boot:spring-boot-starter-test'
}
Просто для подтверждения, вы проверили свое заявление об импорте! –
Все аннотации импортированы правильно. Для JdbcTemplate я дважды проверял себя. –
Я забыл упомянуть в вопросе, я использую Spring 4.3.5.RELEASE. Я развивался для продукта POC. –