Could you please help me to get rid of ApplicationContext
?
I have a factory so that all book instances are spring-beans. I think it's a good decision to make all beans spring-beans.
@Component
public class BookFactoryImpl implements BookFactory {
private final ApplicationContext applicationContext;
@Autowired
public BookFactoryImpl(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Book createBook(String name) {
return applicationContext.getBean(Book.class, name);
}
}
Here is a configuration class with a @Bean
method that is used to instantiate a new instance of Book
class:
@Configuration
@ComponentScan({"factory"})
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Lazy
public Book book(String name) {
return Book.builder().name(name).build();
}
}
Here is my Book
entity class:
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
@Builder
public class Book {
@Id
@GeneratedValue
private int id;
@Basic(fetch = FetchType.LAZY)
private String name;
}
I have more one idea - to annotate BookFactoryImpl
with @Configuration
and move @Bean
method in it but in this case, my factory will be turned into @Configuration
class with the broken lifecycle.
What do you think, what is the best way to implement a factory and how to reduce external dependencies like ApplicationContext
?
Or maybe it's nice to make all factories as @Configuration
classes with @Bean
methods, how do you think?