@Primary
@Component
public class PetrolEngine implements Engine
{
// Implementation
}
@Configuration
public class AppConfig
{
@Bean
@Primary
public Engine petrolEngine()
{
return new PetrolEngine();
}
@Bean
public Engine dieselEngine()
{
return new DieselEngine();
}
}
package in.sp.beans;
public interface Engine
{
void start();
}
// Diesel Engine Implementation
package in.sp.beans;
import org.springframework.stereotype.Component;
@Component
public class DieselEngine implements Engine
{
@Override
public void start()
{
System.out.println("Diesel Engine started...");
}
}
// Petrol Engine Implementation with @Primary
package in.sp.beans;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
public class PetrolEngine implements Engine
{
@Override
public void start()
{
System.out.println("Petrol Engine started...");
}
}
package in.sp.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Car
{
private Engine engine;
@Autowired
public Car(Engine engine)
{
this.engine = engine;
}
public void drive()
{
engine.start();
System.out.println("Car is running...");
}
}
// Configuration Class
package in.sp.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "in.sp.beans")
public class AppConfig
{
//no bean configuration required
}
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();
}
}
Petrol Engine started... Car is running...
Aspect | @Primary | @Qualifier |
---|---|---|
Scope | Works globally across the application. | Used at specific injection points. |
Usage | Sets a default bean for injection. | Explicitly selects a specific bean. |
Precedence | Lower | Higher |
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.