Spring @ConditionalOnResource Example

Condition On Resource

In this tutorial I will create examples on Spring @ConditionalOnResource. The @ConditionalOnResource annotation lets configuration be included only when a specific resource is present in the classpath. For example, the Log4j class is only loaded if the log4j configuration file (log4j.properties) was found on the class-path. This way, you might create similar modules that are only loaded if their respective configuration files have been found on the class path.


Java 12/19, Maven 3.6.3/3.8.5, Spring Boot 2.1.7 – 2.4.5/3.1.5

Project Setup

Create a maven based project in your favorite IDE or tool with the project name as spring-conditional-on-resource.

I will update the build file (pom.xml) as follows to include the spring boot dependencies.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">






Log4j Class

Create a simple Log4j class just to check whether it is loaded or not based on condition.

public class Log4j {


Spring Config

Create below SpringConfig class to load the Log4j class conditionally.

So if log4j.properties file is found in the classpath then only Log4j class will be loaded otherwise not.

@ConditionalOnResource(resources = { "log4j.properties" })
class SpringConfig {

	public Log4j log4j() {
		return new Log4j();


Main Class

Create main class to test the Spring Boot application for @ConditionalOnResource.

public class SpringConditionalOnResourceApp implements CommandLineRunner {

	private ApplicationContext applicationContext;

	public static void main(String[] args) {
		SpringApplication.run(SpringConditionalOnResourceApp.class, args).close();

	public void run(String... args) throws Exception {
		String[] beans = applicationContext.getBeanDefinitionNames();


		boolean contains = Arrays.stream(beans).anyMatch("log4j"::equalsIgnoreCase);

		if (contains) {
			System.out.println("Log4j loaded");
		} else {
			System.out.println("Log4j not loaded");


Testing Condition On Resource

Now if you run the above main class, you will see below output:

Log4j not loaded

Now if you put the log4j.properties file under classpath directory src/main/resources then you will see below output, but it depends on you how you are going to configure the log4j config file.

Log4j loaded

Source Code


Leave a Reply

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