How to load jar files when running javac to compile Java class which imports some libraries?

Below is the structure of my very basic sample Spring framework application.


Below is the sample Java class which import some Spring Framework libaries.

import org.springframework.beans.factory.BeanFactory;  
import org.springframework.beans.factory.xml.XmlBeanFactory;  

public class Test {  
    public static void main(String[] args) {  
        Resource resource=new ClassPathResource("applicationContext.xml");  
        BeanFactory factory=new XmlBeanFactory(resource);  

        Student student=(Student)factory.getBean("studentbean");  

When I try to compile this Test Java class by running this command javac -d ., I get the following errors:

 error: package org.springframework.beans.factory does not exist
 import org.springframework.beans.factory.BeanFactory;

 error: package org.springframework.beans.factory.xml does not exist 
 import org.springframework.beans.factory.xml.XmlBeanFactory;

 error: package does not exist

 error: package does not exist

I think this is because I did not load the Spring framework jar files in the libs directory. When I run the following command, it kind of solves one error:

javac -cp libs/org.springframework.beans-3.0.1.RELEASE-A.jar -d .

If I run javac -cp libs/*.jar -d ., I get the following errors:

error: invalid flag: libs/[EACH JAR FILE].jar
Usage: javac <options> <source files>

How do I load (multiple) jar files when trying to compile Java class with javac?

Actually, there are different ways to mention the <path-to-jar> and it is dependent on the OS. For Mac you have to mention it in double quotes "<path-to-jar>"

javac -cp "libs/org.springframework.beans-3.0.1.RELEASE-A.jar" -d .

or you can use -classpath

javac -classpath "libs/org.springframework.beans-3.0.1.RELEASE-A.jar" -d .

For Ubuntu, you have to use semi colon <path-to-jar>;

javac -cp libs/org.springframework.beans-3.0.1.RELEASE-A.jar; -d .

Instead, you can add all dependency jar files in the environment variables to save yourself from the redundant task of mentioning it every time.

If you have multiple jar files inside a directory and you want to compile a java class, you can do it in the following manner.

javac -classpath lib/* <path to java file>/

In my case, I tried like this and it is working fine for me.

javac -classpath lib/* E:/kafka-dev-2019/kafkaexample/src/main/java/com/devglan/kafka/

In this case, there is no need to mention each and every jar file.