Home > front end >  Is it possible to inject a record with Spring?
Is it possible to inject a record with Spring?

Time:05-10

I have found plenty of examples of constructor injection into record types. However, I haven't seen anyone address injecting a record into another class. Is this possible? When I try it I see errors about the class being final. But I'm struggling to make sense of this because I'm not trying to extend it or use AOP, or anything else where I would expect the class to be extended.

CodePudding user response:

A record is final, so it probably can't be annotated with @Component or another similar annotation (although I haven't tried). It can be returned from a bean method that's annotated with @Bean though, and that makes it eligible for injection.

public record Person (String name, int age) {}
@Configuration
public class MyBean {

    @Bean
    public Person person() {
        return new Person("John Doe", 30);
    }
}
  • Related