java - Spring - Don't create bean if a primary bean is present -


is possible prevent creation of bean of type a if generated primary bean

example:

i have 2 configuration classes , have 2 profiles.

appconfig.java: (the generic configuration class having beans)

@configuration public class appconfig {     @value("${host}")     private string host;      @bean     public geta() {         //uses 'host' value create object  of type        // involves database connections     }      @bean     public b getb(a a) {  //others using bean a. might come either geta() or getothera()         ...     }  } 

specificconfig.java: (these beans created if profile-a active)

@configuration @profile("profile-a") public class specificconfig{     @bean     @primary     public getothera() {      //return bean of type     } } 

here when profile-a chosen, bean of type a come specificconfig.java. problem when profile-a active parameter host in appconfig.java not available , hence geta method in appconfig throws exception.

since bean of type there or there (i'm not sure of order of bean creation), don't want geta() in appconfig executed. (when profile-a active)

is there way achieve this?

possible solutions:

  1. add @profile({"!profile-a"}) top of geta method in appconfig.

  2. add if checks see if host param exists.

    i don't want above 2 have change in multiple places. (there bunch of other beans a , other params host)

thanks

let me know if clarification required.

the condition annotations of spring boot auto-configuration solution constrain bean creation.

  • @conditionalonbean : check specified bean classes and/or names contained in beanfactory.
  • @conditionalonproperty : check specified properties have specific value

example:

@configuration public class specificconfig{    @bean    @conditionalonbean(a.class)    @primary    public getothera() {     //return bean of type    } } 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -