Which is the Spring equivalent for the CDI @Produces annotation?

Renato Dinhani picture Renato Dinhani · Sep 16, 2014 · Viewed 11.1k times · Source

When I was working with CDI, I could use the @Produces annotation to create a producer method to be called to choose which bean that implemented an interface would be injected by the @Inject annotation .

Now I am working with Spring, but I didn't find anything similar. What I need to use to achieve the same result I had with the @Produces annotation in CDI when I use the @Autowired annotation?

Answer

Luiggi Mendoza picture Luiggi Mendoza · Sep 16, 2014

You're looking for @Bean:

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/>, such as: init-method, destroy-method, autowiring, lazy-init, dependency-check, depends-on and scope.

Example (taken from link above):

@Configuration
public class AppConfig {
    //similar to @Produces CDI annotation
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

I suggest you to pay a read to this: Spring DI and CDI comparative study