sts4 icon indicating copy to clipboard operation
sts4 copied to clipboard

@Profile not working as expected

Open dbnex14 opened this issue 3 years ago • 0 comments

Describe the bug I have 3 application.profiles files:

  • application.profiles (root for common settings including spring.profiles.active=prod)
  • application-dev.profiles (specific database settings for H2 and myapi.profile=dev)
  • application-prod.profiles (specific database settings for DB2 and myapi.profile=prod)

I also have a CommandLineExecutor component like:

@Profile("dev")
@Component
public class CommandLineExecutor implements CommandLineRunner {

  @Autowired
  private MyRepo myRepo;

  @Override
  public void run(String... args) throws Exception {
    // inserts initial data into in-memory H2 database for development purposes using Spring JPA
    myRepo.save(new MyEntity(....);
  }
}

Since this component is annotated with @Profile("dev") annotation, I would expect this bean to belong only to my 'dev' profile so that when spring.profiles.active=dev, it would execute and seed H2 database with some basic data I need for development. This is good and working.

However, if I set active profile to prod using spring.profiles.active=prod, then CommandLineExecutor should not execute. I need this in order to avoid populating production database with data I need for development. However, CommandLineExecutor still executes even though it is annotated with @Profile("dev") and attempts to insert data which I can see when I run maven > install. Also, my CommandLineExecutorTest runs

Maven > Install then shows errors like below. These errors are OK as I have additional security on database level to prevent inserting data into prod database but they show that the CommandLineRunner and CommandLineRunnerTest are both running regardless of the @Profile annotation:

java.lang.IllegalStateException: Failed to execute CommandLineRunner
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-150, SQLSTATE=42807, SQLERRMC=null, DRIVER=4.29.24

ERROR] Errors:
[ERROR] CommandLineExecutorTest.whenContextLoaded_CommandLineRunnerRuns » IllegalState
[INFO] 
[ERROR] Tests run: 8, Failures: 0, Errors: 1, Skipped: 0

To Reproduce N/A

Sample N/A

Reports that include a sample will take priority over reports that do not. At times, we may require a sample, so it is good to try and include a sample up front.

dbnex14 avatar Oct 19 '21 16:10 dbnex14