Sobes.tech
Junior — Middle

How can the same business logic be applied to different Bean components in Spring, avoiding code duplication?

sobes.tech AI

Answer from AI

To apply the same business logic to different Bean components in Spring and avoid code duplication, several approaches can be used:

  1. Extract common logic into a separate service or component — create a separate class with business logic and inject it into the necessary Beans via @Autowired.

  2. Use inheritance — create a base class with common logic, and extend this class in components.

  3. Apply aspect-oriented programming (AOP) — extract common logic into an aspect that will be applied to the necessary methods of different Beans.

Example with a service:

@Service
public class CommonBusinessLogic {
    public void execute() {
        // common business logic
    }
}

@Component
public class BeanA {
    private final CommonBusinessLogic commonLogic;

    @Autowired
    public BeanA(CommonBusinessLogic commonLogic) {
        this.commonLogic = commonLogic;
    }

    public void doWork() {
        commonLogic.execute();
        // specific logic for BeanA
    }
}

@Component
public class BeanB {
    private final CommonBusinessLogic commonLogic;

    @Autowired
    public BeanB(CommonBusinessLogic commonLogic) {
        this.commonLogic = commonLogic;
    }

    public void doWork() {
        commonLogic.execute();
        // specific logic for BeanB
    }
}

This approach allows centralizing business logic and reusing it across different components.