在Spring Boot 2.0.2版本中注入特定的数据源

时间:2018-11-13 16:39:17

标签: spring spring-boot spring-data-jpa spring-jdbc hikaricp

当尝试使用 Spring Boot 2.0.2 RELEASE 自动连接 DataSource 时,会出现以下错误,并且无法进行注入:

'无法自动接线。 “ DataSource”类型的bean不止一个。

在DataSourceConfiguration类中为HikariDataSource,BasicDataSource和Tomcat创建bean。

是否有一种方法可以使其中一个合格,并避免创建其余的一个?

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public SecurityConfig() {
        this.usersByUsernameQuery = // definitions here
        this.authoritiesByUsernameQuery = //
        this.allowedAuthorities = //
    }

@Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth, final DataSource dataSource) throws Exception {
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery(usersByUsernameQuery)
            .authoritiesByUsernameQuery(authoritiesByUsernameQuery);
    }
}

pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
</dependencies>

application.properties:

spring.datasource.url=jdbc:mysql://localhost:9400/test
spring.datasource.username=root
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

0 个答案:

没有答案