Issue
In JavaConfig I have defined Conditional Beans using @ConditionalOnProperty
like below, so that when couchbase.multiBucket.t1CBProvider
is defined in property file then only bean t1CBProvider
will be created.
@Bean("t1CBProvider")
@ConditionalOnProperty(prefix = "couchbase.multiBucket", name = "t1CBProvider")
public ICouchbaseDTOProvider provider() {
return new CouchbaseDTOProvider("t1CBProvider");
}
now in one of the Java class ArchiveRepo
I have Injected the class as below, so that I can use this. There are various other Bean Injections & Methods are defined in ArchiveRepo
class,so I need it even if CouchbaseDTOProvider
is not created by JavaConfig.
public class ArchiveRepo{
.
@Inject
@Qualifier("t1CBProvider")
private ICouchbaseDTOProvider t1CBProvider;
...
Now, if couchbase.multiBucket.t1CBProvider
value not defined in properties file bean CouchbaseDTOProvider
will not be created and we will get No Such Bean Found Exception. How can we restrict the dependency injection of ICouchbaseDTOProvider
in such a way that, if bean is not created dependency injection on bean is also restricted or made in-effective and we dont have any issue while creating an object of 'ArchiveRepo` class.
Solution
You can either do @Autowired(required = false) as one suggested in the comment or define this variable with optional as you can see below:
public class ArchiveRepo{
.
@Inject
@Qualifier("t1CBProvider")
private optional<ICouchbaseDTOProvider> t1CBProvider;
...
Answered By - Tal Glik