简体   繁体   中英

Spring boot : bean creation profile specific

I am working on a spring boot application.i am using spring boot version: 2.2.4-RELEASE

I am trying to create a bean specific for a profile.but the bean is not creating as expected.

Below is my configuration file:

@Configuration
@Slf4j
public class TestConfig {

  //below is the bean i need to be created for dev and test
  @Bean
  @Profile({“dev”, “test”})
  TestObject getTestObject() {

        //do something
  }

//below is the bean i need to be created for staging and prod
  @Bean
  @Profile({“staging”, “prod”})
  TestObject getTestObject() {

        //do something
  }


//someother beans common for all profiles

}

Service.java

@Service
public class Serviceclass {

  @Autowired
   private TestObject testObj;

   //some methods

}

I tried the above way, but the bean is Not getting created for any of the profiles. Any suggestions on how to achieve this would be helpful.

Update : the application is failing to start as one of the service class has dependency on the bean i am trying to create.

Thanks in advance.

In the note found in

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html

Use distinct Java method names pointing to the same bean name

You have to active profile for the application. You can pass runtime argument as as -Djava.profiles.active=dev . It will solve your problem. Also, need to create environment specific property files like application-{env}.properties

I think the problem is the same method name. For some reason if i give the same name (method overloading) we are running into issues. Found a similar thread which explains the same.

Thanks a lot everyone who tried to solve the issue.

Note: i will try to find the thread and will update the thread here which explains the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM