2

I am looking into a codebase where every POJO has been managed by spring and injected using lookup annotation.

@Lookup
public Publisher getPublisher() {
    return new Publisher();
}

@Lookup
public Book getBook() {
    return new Book();
}

These Publisher and Book objects are nothing but POJO with just getter/setters. These classes are spring managed as prototype beans. I am thinking, it is over use of lookup annotation and overhead where we could just use factory methods or simply create new instance. Do you think using lookup annotation for this use case useful/efficient?

cosmos
  • 2,143
  • 2
  • 17
  • 27
  • why don't you annotate the Publisher class as componenet or service and autowire it when you use it? here is something i got for you. https://stackoverflow.com/questions/29239965/spring-bean-with-lookup-method – sam Apr 24 '18 at 14:41
  • I think you didn't get the question. Publisher is in fact annotated as component and as prototype scope. I am asking doing that to a POJO and using `@Lookup` is overkill. – cosmos Apr 24 '18 at 14:46
  • I think you can ditch Lookup n use @Qualifier in your Autowired objects. – sam Apr 24 '18 at 14:53

1 Answers1

1

In a general way, making instances of a class some spring beans is not relevant if these beans never be needed to take advantage of Spring features and if these beans never be injected in other beans or never needs to inject other beans in their own instance.

@Lookup is the annotation-based way of the the old XML lookup-method attribute. Besides beans created with this annotation also have multiple limitations. For new projects I never use it.
As alternative as you need to declare beans in the java class the @Bean annotation that creates "not limited" beans should generally be favored instead of.

EDIT :

I wrote an answer to a very related question yesterday : Spring - is using new a bad practice?.
I just updated it to be more exhaustive.

davidxxx
  • 125,838
  • 23
  • 214
  • 215