@Qualifier
annotation to identify the correct bean. @Autowired
or similar annotations like @Inject
. @Autowired
public Car(@Qualifier("petrolEngine") Engine engine)
{
this.engine = engine;
}
@Autowired
@Qualifier("electricEngine")
public void setEngine(Engine engine)
{
this.engine = engine;
}
@Autowired
@Qualifier("dieselEngine")
private Engine engine;
package in.sp.beans;
public class Engine
{
private String type;
public Engine(String type)
{
this.type = type;
}
public void start()
{
System.out.println(type + " engine started...");
}
}
package in.sp.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class Car
{
private Engine engine;
// Setter method for dependency injection with @Qualifier
@Autowired
@Qualifier("dieselEngine") // Specify the exact bean to inject
public void setEngine(Engine engine)
{
this.engine = engine;
}
public void drive()
{
engine.start();
System.out.println("Car is running...");
}
}
package in.sp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import in.sp.beans.Engine;
@Configuration
@ComponentScan(basePackages = "in.sp.beans")
public class AppConfig
{
// Define multiple beans of the same type
@Bean(name = "petrolEngine")
public Engine petrolEngine()
{
return new Engine("Petrol");
}
@Bean(name = "dieselEngine")
public Engine dieselEngine()
{
return new Engine("Diesel");
}
}
package in.sp.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import in.sp.beans.Car;
public class MainApp
{
public static void main(String[] args)
{
// Load Spring context from Java-based configuration
ApplicationContext context = new AnnotationConfigApplicationContext(in.sp.config.AppConfig.class);
// Retrieve the Car bean
Car car = context.getBean(Car.class);
// Call the drive method
car.drive();
}
}
Diesel engine started... Car is running...
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.