So che avvio la primavera creerà una Bean dataSource
automaticamente se le configurazioni relative si trovano in application.properties
, come:Perché DataSource non può essere avviato automaticamente nell'applicazione di avvio di primavera?
spring.datasource.url = jdbc:mysql://192.168.10.103:3306/hms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
[email protected]
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
Codice funzione:
package com.synline.mdataserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.apache.tomcat.jdbc.pool.DataSource;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
AnnotationConfigApplicationContext context;
/*@Autowired
DataSource dataSource;*/
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
DataSource dataSource = (DataSource)context.getBean("dataSource");
System.out.println(dataSource);
while (true) {
Thread.sleep(5000);
}
}
}
Se il @Autowired DataSource è commentata, la Le informazioni sul bean saranno stampate:
[email protected]{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}
Quindi penso che Spring Boot reall hai creato il fagiolo.
Ma se si usa @Autowried DataSource, un'eccezione si verifica a lamentarsi No Such Bean
Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.tomcat.jdbc.pool.DataSource com.synline.mdataserver.Application.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.apache.tomcat.jdbc.pool.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Si prega di inviare il caso completo che non funziona, non solo uno snippet. Inoltre dovresti usare un 'javax.sql.DataSource', non il tipo di tomcat specifico. –
Grazie. Rendo nuovamente il post e aggiungo il codice completo. –
Ah, Deinum, hai capito. Dopo aver "importato javax.sql.DataSource", invece di "import org.apache.tomcat.jdbc.pool.DataSource;", non ci sono più problemi! –