Aseem Bansal
Aseem Bansal

Reputation: 6972

Why is overriding spring bean declared in one config allowed in another config?

I am starting to learn Spring and came across a feature of Spring - overriding spring bean declared in one xml config in another config.

I do not understand where this feature can be useful. It seems illogical because same container will be configured using two different xmls and even when there are two beans with same ID, instead of reporting the ambiguity it is defaulting to the last one.

Is there a practical scenario where this can actually be useful? Is this good practice?

Upvotes: 0

Views: 1368

Answers (1)

M. Deinum
M. Deinum

Reputation: 125252

There are reasons why this could be useful for instance

  • Testing
  • Developing Component Libraries

Testing

When testing you can choose to override 1 or more beans. For instance a DataSource you probably don't want to test against the production instance of your database. But maybe an in memory one or one specially for testing. For this you can then just override the DataSource bean.

Developing Component Libraries

You can provide a starting configuration for your libraries and let users override certain components or let them implement interfaces. A sample of this is how the different Spring portfolio projects work (Spring Security, Spring Batch) with their default configuration.

Also when overriding beans spring will log this at startup of your application.

Upvotes: 1

Related Questions