Home > database >  Create a data source based on the spring profile
Create a data source based on the spring profile

Time:10-12

I have two profiles in Spring: first and second. If I use the first profile, I want to create a datasource based on postgres, but if I use second I don't want any datasource created at all. I've defined my JpaEntityConfig class as:

@Configuration
@ConfigurationProperties()
public class JpaEntityConfig {

    @Autowired
    DataSource dataSource;

    public DataSource dataSource() {
        return dataSource;
    }

    ...
}

if I set spring.profiles.active=first then it works fine, however if I set it to spring.profiles.active=second then I'm getting the following error:

Field dataSource in com.package.JpaEntityConfig required a bean of type 'javax.sql.DataSource' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:
Consider defining a bean of type 'javax.sql.DataSource' in your configuration.

how can I get around this?

CodePudding user response:

As JpaEntityConfig is expecting a DataSource you can make this optional if you so wish

@Configuration
@ConfigurationProperties()
public class JpaEntityConfig {

    @Autowired(required = false)
    DataSource dataSource;

CodePudding user response:

@Configuration
@ConfigurationProperties()
@Profile("!second")
public class JpaEntityConfig {

    @Autowired
    DataSource dataSource;

    public DataSource dataSource() {
        return dataSource;
    }

    ...
}

You can skip this jpa configuration when profile second is active as above.

  • Related