1. Overview

Spring framework makes our very easy work to creating beans and accessing those beans in teams of scopes as well. But so many times we need to create beans based on some conditions like properties values and resources which are available on the classpath and etc. In this article, we are going to discuss to create conditional beans if particular resource available in the classpath.  Resources might be any resources like text file, properties file, XML file, and any other configuration file.

i.e Spring internally use these configurations at so many places, for example, if logback.xml file available in classpath then spring will use logback logs configuration otherwise it will use default log configurations.

2. Spring ConditionalOnResource  Example

  1. @ConditionalOnResource is annotation using that we can create a bean if specified resource found otherwise it will not create a bean. We can specify resources location of classpath as well as system locations like:  @ConditionalOnResource(resources = "file:\\C:\\data\\example.json") . Make sure that, If we want to point to file system instead of classpath then resources name should start with file:\\.
  2. @ConditionalOnResource annotation also supports condition on multiple resouces, It will create bean only if all the resources must exist at specified locations: @ConditionalOnResource(resources = {"classpath:example.json","classpath:example1.json"})
  • Here @ConditionalOnResource(resources = "classpath:example.json") indicates that create the bean if indicated file found in classpath otherwise bean will not be created.
  • @ConditionalOnMissingBean indicates that example.json not found in class so above bean will not be created in that case default bean for ExampleService will be created with a default value. It’s not compulsory to write  @ConditionalOnMissingBean configurations but we do not have invert condition of @ConditionalOnResource in spring.
package com.javadeveloperzone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
 * Created by JavaDeveloperZone on 06-16-2019.
public class SpringBootConfig implements CommandLineRunner{
    private ExampleService exampleService;
    public static void main(String[] args)  {
        SpringApplication springApplication = new SpringApplication(SpringBootConfig.class);
    @ConditionalOnResource(resources = "classpath:example.json")
    ExampleService exampleService() throws Exception{
        System.out.println("Creating bean of example json from example.json...");
        File file=new ClassPathResource("example.json", this.getClass().getClassLoader()).getFile();
        return new ExampleService(new String(Files.readAllBytes(Paths.get(file.toURI()))));
    ExampleService exampleServiceNo() throws Exception{
        System.out.println("ExampleService bean not found so creating default bean");
        return new ExampleService("{name:developer}");      // default value
    public void run(String... args) {
        System.out.print(exampleService.getJson());   // it will print value

3. Conclusion

In this article, We learn about how we can create beans with @ConditionalOnResource  annotation and based on the particular condition of resources, resources files might be inside the classpath or as a file system resources. We have also seen an example where spring internally used  @ConditionalOnResource annotation. @ConditionalOnMissingBean annotation is used to create bean is it does not exist in spring content.

4. Source Code

5. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *