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?
CDI is a multi-vendor standard implemented by several different companies and products (Weld, OpenWebBeans) that has been in Java EE since version 6 and Jakarta EE since version 8. Both Spring and CDI implement the JSR-330 specification, but beyond that have absolutely nothing to do with one another.
Spring already supports CDI's javax.
Contexts and Dependency Injection for Java EE (CDI) is one of several Java EE features that help to knit together the web tier and the transactional tier of the Java EE platform.
To summarize: CDI is nothing like a "replacement" for the Spring ecosystem, it's rather an improvement over Spring's dependency injection mechanism. It's part of Java EE 6, so if you are on a GlasFish with Java EE 6, you should definitely go for CDI.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With