27

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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199

1 Answers1

32

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

Slaw
  • 37,820
  • 8
  • 53
  • 80
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 1
    Beware of one major difference - a CDI producer has access to InjectionPoint, which allows it to do some additional tricks. –  May 02 '17 at 19:01
  • You can also use @Autowired for passing elements that need to be injected in the bean and set them. – Luiggi Mendoza May 02 '17 at 19:02
  • 1
    With CDI it's possible to inject primitive types or objects that are not beans themselves. Is that also valid with Spring? Also when I got this right, the concepts are different: while CDI allows for every bean to produce an injectable object, in Spring only classes annotated with @Configuration can produce Beans (otherwise in Lite mode). The intentions are different... – Wecherowski Jul 18 '17 at 18:50
  • @Wecherowski Spring does allow you to inject primitive types using [`@Value`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html). – Luiggi Mendoza Jul 18 '17 at 19:50