Card 05/ 07
@Bean Methods Example: Registering a Class You Cannot Annotate
A class from someone else's library becomes a bean through a method that builds and returns it.
A @Bean method is a method in a @Configuration class whose return value the container registers as a bean. It is how you make a bean out of a class you cannot annotate, such as one that ships inside a library.
LegacyRideGateway ships inside a jar (a packaged Java library) that your project depends on. You cannot add @Component to it because there is no source to edit, so component scanning will never find it:
// no source available — cannot be annotated
class LegacyRideGateway {
LegacyRideGateway(String endpoint) { /* ... */ }
void call() { /* ... */ }
}
@Configuration
class GatewayConfig {
@Bean
LegacyRideGateway legacyRideGateway() {
return new LegacyRideGateway("https://legacy.internal/rides");
}
}calling legacy gateway at https://legacy.internal/ridesThe container calls legacyRideGateway() once at startup and registers what it returns, so the gateway can be injected into any other bean exactly like one found by scanning. The method is ordinary Java, which also lets it pass constructor arguments, such as the endpoint, that scanning could not supply.
So scanning covers your own classes, and @Bean methods cover everything else, including classes that need configuration to be constructed.
← → move through sections and cards