The Real Benefits of Java EE CDI

I'm new to Java EE and I'm wondering what are the real benefits of using CDI (@Named, @Inject). Of course, I asked Google. But I've always gotten general answers like "loose communication" and "test better". But I think that in order to get a free connection, no structure is needed.

In my small project I am using three classes

public interface UserIf
{
    ...
}

@Named
public class User implements UserIf
{
     ...
}

public class Main
{
    @Inject
    UserIf user;
}

      

Now I can easily introduce a different UserIf implementation. But I could also do it with

public class Main
{
    UserIf user = new User();
}

      

This architecture is easy to change. Just write another UserIf implementation and change

UserIf user = new User();

      

to

UserIf user = new AnotherUserImpl();

      

I don't see the benefit of using CDI here. When I think of a larger EAR project consisting of some EJBs and WARs, it might be easier to use multiple modules (EJBs, WARs) if they are bundled together. But as far as I know, it is not possible to use CDI unless the classes are in the same bank / war. So what would be the real setup when you get real benefits from using CDI?

Cheers Helmsen

+3


source to share


2 answers


The fact is that if you need to rename, for example, AnotherUserImpl

or you want to switch to a different implementation, then you need to go to all the classes that use this imp and rename. With CDI qualifiers, you are everywhere

@Inject
@AnotherUser
private User user;

      



The client code doesn't know anything about the implementation User

, so you can change it however you want on the business side and the client won't even notice. The loose coupling principle is that the client that is using your API doesn't really know about the implementation, it's configured to be external (think CDI vendors or Spring XML configuration). There are also other benefits of CDI such as producers, interceptors, new transaction API, alternatives, or others.

+4


source


I am honestly jumping up to close this as unconstructive / opposed. But there are some facts to help you understand a little better.



  • CDI works through JARs and WARs in EAR. The problem has to do with the definition @ApplicationScoped

    , where in the EAR each of the EJB-JAR modules and WAR modules is technically defined as its own application.

  • The type of question you are asking is more about what specifically has to do with dependency injection / inversion rather than CDI. Not everyone will want to use these paradigms, but realistically they are the norm.

  • The built-in scope model allows you to control when an instance is created more declaratively rather than programmatically. In CDI, applying a scope to a bean is annotation. This means that the bean becomes available to you.

0


source







All Articles