r/SpringBoot • • Dec 27 '24

Object of interface in Java?

The @Component annotation is used to create a bean, and annotations like @Repository, @Service, and @Controller are specialized forms of @Component. They mark a class for automatic bean creation and registration in the Spring loC context. However, when using interfaces (such as with @Repository), we cannot directly instantiate an interface. So, how does Spring create an instance of a class annotated with @Repository, especially when the class is defined as an interface?

37 Upvotes

15 comments sorted by

View all comments

13

u/[deleted] Dec 27 '24 edited Apr 17 '26

Protecting my online privacy by running Redact regularly to batch delete old content. It handles Reddit, Discord, Twitter, Instagram, data brokers and a whole lot more.

continue repeat library amusing rinse chief vase retire skirt instinctive

3

u/blocknspike Dec 27 '24

Thanks for the reference. Either I am very weak in Java Springboot Or the article is explained hard way. Not able to understand much out of it.

17

u/zontapapa Dec 27 '24

At run time spring will create an implementation of that interface with generated code to match the contract of your @Repository interface methods and then register and instance of this implementation as a spring bean. Anywhere you want to inject the repository, you declare a field of interface type, the dynamically added bean is a matching candidate and is made available/injected. The implementation of your interface and its methods is only in memory. Spring does not write class created from your interface to disk

2

u/blocknspike Dec 27 '24

Thaks, now I can visualize the stuff.

6

u/alex98tenismenu Dec 27 '24

I think MapStruct works in a similar way but it creates the class at compile time.

3

u/[deleted] Dec 27 '24 edited Apr 17 '26

Plot twist: this post no longer exists because Redact swept through and cleared it out along with everything else. Social media, messaging apps, people finder sites, all of it.

square include strong dinosaurs familiar beneficial aspiring oatmeal groovy payment

2

u/blocknspike Dec 27 '24

I don't think Mapstruct(annotation processor) uses reflection. Reflection is concept of runtime. I am not sure if in compile time you can get field matches using Reflection I never heard that. Please share the reference for the same if any.

2

u/[deleted] Dec 27 '24 edited Apr 17 '26

Deleted with Redact because data brokers don't deserve my content. Mass removal across Reddit, Discord, X, Instagram and all major social media platforms.

teeny weather support heavy office capable bake shy amusing quiet

2

u/blocknspike Dec 27 '24

Also it do not uses reflection for runtime dynamics that dynamic proxy uses.