JBoss cdi-api uses - jboss

I was looking for some help on CDI APIs. I'm sorry if my question looks naive, I tried looking on net for some high level description on CDI APIs, but couldn't get it right.
The javadoc says:
Contexts and Dependency Injection (CDI) defines a set of complementary services that help improve the structure of application code.
My question is in EJB 3.X we already have Annotations for helping with DI and injecting resources like PersistenceContext and other kind of resources. So where exactly the CDI APIs will be helpful? In plain web-app/standalone Java programs using J2SE?

EJB 3.0 comes with dependency injection on resource- and EJB-level - which is pretty cool already :-)
What CDI does (and which is even cooler) - it lowers the barrier to dependency injection to so-called "managed beans" (JSR 316) - which (among others) defines the minimal set of preconditions a class needs to benefit from dependency injection. Just slightly simplifying, one can say that all classes in a CDI project are managed beans and therefore are eligable for DI.
To summarize what CDI brings over EJB 3.0 in terms of DI:
you don't need EJBs anymore, CDI basically works with POJOs. That's truly lightweight, because it allows you to use EJBs when you need EJB, not when you need DI.
DI turns stateful - different dependencies live in different scopes - something EJB 3.0 completely fails to deliver.
you can benefit from a typesafe and loosely coupled interceptor mechanism
you can benefit from a typesafe and loosely coupled mechanism
Have a look at the first chapter here, and you'll get the idea :-)

DI in Java EE5 allows you inject only resources like JDBC DataSource, JPA EntityManager, UserTransaction, Web Services, EJBs etc. All this resources was managed by container.
With EE6 and with CDI in particular you aren't restricted to inject only resources - you can inject everything (every bean). Look at annotations which come with CDI specification: #Inject, #Named, #Scope, #Singleton etc.
CDI give you features like events, decorators etc.
Look at this tutorial, it should help you to understand CDI: http://java.dzone.com/articles/cdi-di-p2

Related

Guice with JAX-RS

I am using Guice as my dependency injection framework. I'd like something that I can add that will make creating REST services easier.
I've had a look at guice-servlet and it works well for directing paths to HTTP servlets, but that's all it appears to do, I was expecting a JAX-RS like annotation syntax to work but it doesn't.
Having not actually used JAX-RS I've googled around and it appears that Jersey is the reference implementation for this but it looks like it uses its own dependency injection framework and doesn't work well with Guice. In addition it has 5+MB worth of dependencies which seems alot for what I am after.
Is Guice designed in such a way that it doesn't lend itself to JAX-RS, if so what else should I be doing?
I think that maybe the guice-servlet module has misguided you. Guice is a DI framework. Period. The real goal of the guice-servlet module is not providing the servlet's and filter's shortcut declaration but giving support for the special scopes request and session. Those nice shorcut declarations are syntatic sugar.
Chosing a JAX-RS implementation in Java is a bit out of the question. You have several options (Jersey, Resteasy, Spring...). If you are going full JavaEE then you don't have to choose. You just use the annotations (and the DI) out of the box.
If you are not using a JavaEE server (just a web server like Tomcat or any other fancy thing like an Android app) then you must choose your implementation. If you are using DI also (which I recommend) then there is one more decision to make.
So you are not using JavaEE and you want to implement some REST API using JAX-RS and dependency injection. You do some research and end up choosing Jersey and Guice. Good choice, I've chosen those in my last projects too. Yes, the dependency graph of Jersey is a bit bloated. I know, it could be way better.
Now your problem is how to make it work together because Jersey uses it's own DI framework (HK2) which is a bad thing.
You have a lot of references on SO about Jersey-Guice integration. Your best bet is the Guice HK2 bridge.
What? You want a direct reference on SO? No problem, here is a good one. Don't forget to upvote the answer. ;-)
Jersey and Google Guice integration

Configuring Entity properties

In a Java EE project, I've found a recurrent solution for configuring the application that consists on the use of #Injection of primitives/Strings on managed beans, avoiding external dependencies on that way.
What about #Entity? Is there some "good practice code" for configuring entities using only Java EE (no Spring)?
CDI does not support injection into objects that are not created by the CDI container (more info here). Since entities are created by JPA provider when they are loaded from the DB, CDI would obviously not work.
So, in plain Java EE world your only options are to move the logic depending on the injected resources out of the entities, or to access the resources via static methods from within the entities. Keep in mind the increased complexity when testing the entities if static state/methods are used.

Java EE DAO without EJB

Is it possible to create a DAO in Java EE environment, which uses JPA, but does not need to be a Stateless bean? I am asking because I have a huge number of EJBs, just because I need a few #Resources in the DAOs, i.e. EntityManager and so on.
What would you recommend as a way to simplify DAOs in huge project, it seems to me that having a full EJB (instead of a simple object) for a DAO is eccessive.
DAOs are accessed both from other EJBs and from servlets.
It's possible, but not recommended, to inject an EntityManager into other types of beans (like e.g. CDI managed beans) along with a UserTransaction and then manually manage your transactions.
In Java EE 7, JTA 1.2 contributes CDI compatible extensions for declarative transactions just like EJBs have, but at the moment there's no final release of any Java EE 7 AS yet.
it seems to me that having a full EJB (instead of a simple object) for a DAO is excessive.
Why do you think that? A "full" EJB is probably more lightweight than any other alternative, and almost certainly more lightweight than any home cooked thing you can come up with based on an EntityManager.
Don't forget that EJB beans share their resources automatically and that injection points only get proxies. If you mainly use stateless EJB beans, those proxies are akin to URLs, and not the "real" beans. This makes stateless and local EJB beans incredibly lightweight to inject.
Meaning, if you have a given Service where you inject (say) 10 DAOs, that each have an injected EntityManager, and during a given call 3 DAOs are invoked then only 3 beans are actually used and only 1 EntityManager instance. It really is rather efficient.
You can implement DAO as POJO is you want. But the DAO needs an EntitManager which must come from somewhere. Either
you look it up in the POJO with InitialContext#lookup
you pass it in the constructor of the POJO
You must pay attention that InitialContext#lookup will work only if the parent EJB has declared a dependency to the entity manager, even if it doesn't use it.
Whether it's worth the trouble is a judgment call. Local EJB are very cheap, and having many EJB is not a problem for the app server. It's more a problem of understandability by developpers. (See this other answer of me)
Another question to ask is whether you really need the DAOs. With EJB 3, they become very thin layer of logic, and it's worth pondering the pros and cons

Beans, beans, and more beans...what does what?

I've recently been given a project to work on that involves writing a web application. I've never done Java EE before. A lot of resources on the web are dated and I'm having trouble figuring out what the current differences are between the various standards and Java technologies.
Originally I thought I really needed EJB 3.1 due to dependency injection, JPA, session management, and web services. I started experimenting with Glassfish but was told that we had to write the thing in Tomcat. So I've been trying to figure out what I need as well as what and how to put into Tomcat to get there. I've begun to question whether I even need EJB at all.
I want to use JFS, I think, for the MVC architecture. In learning about that I've run into both ManagedBeans and CDI, which according to some renders the former obsolete and also seems to provide all the dependency injection stuff I want to enable unit testing. I've also come to realize that I can get JPA outside of EJB in the form of Hibernate and maybe a few others. Additionally it seems that web services, which I don't know that I need anyway, come in the form of another standard I can't think of the name right now and this also can be installed independently.
My major issue here is session management and state. It seems to me that all which remains for EJB to do is provide #Stateless/#Stateful and #Local/#Remote. However, as I understand it, some of this is already exists in the form of session management in the servlet container...but I don't know how much or what the major differences are that I need to account for in order to decide if I need these things at all.
So my question is, what are the basic, essential differences that I need to know in order to decide if EJB is worth looking at or if I have enough in the form of other libraries and technologies? I've been all over google and Usenet and have not been able to find this information anywhere.
Just thought of another bit. As I understand it, the #Stateful bean annotation provides me thread-safe state saving. I'm probably not going to directly use threads, but I know Java does so behind the scenes a lot and suspect EE especially so. When I need to keep state I don't want to be dealing with threads if this already provides it.
ManagedBean
Java EE 6 has three different ways of defining beans that are managed in one way or another:
#javax.faces.bean.ManagedBean
JSF 2.0 introduced this annotation declaring managed beans in faces-config.xml. This annotation is used to access a bean from the Expression Language.
#javax.inject.Named
In an EE 6 container CDI this annotation is a built-in qualifier types to provide a name to a bean, making it accessible through EL.
#javax.annotation.ManagedBean
This annotation attempts to generalize JSF managed beans for use elsewhere in Java EE.
If you deploy in an EE 6 container (If you use Tomcat or another servlet container, you can also get CDI by adding the Weld jar to your web app), then there is really no reason to use #javax.faces.bean.ManagedBean. Just use #javax.inject.Namedand start taking advantage of CDI sevices.
CDI
One of the objectives of CDI specification is to bring together the Web tier and the transactional services, making easy for developers to use EJB along with JSF in web applications of the Java EE platform.
With CDI you have the following services among others : well-defined lifecycle contexts(influenced by seam 2 and conversation scope), Dependency injection, loose coupling facilities like interceptors, decorators and events and portable extensions, which allows third-party frameworks to integrate in the Java EE 6 environment like SEAM 3 extensions
Managed beans and EJB Services
First of all CDI applies to any managed bean. Some managed beans are EJBs. When we need to use the EJB services in a managed bean, we just add a #Stateless, #Stateful or #Singleton annotation. IMO they act as complementary technologies allowing you to have a flexible and gradual development just only adding some annotations.
So, when should we use a session bean instead of a plain managed bean?
When you need some EJB features that CDI is missing : declarative transactions, concurrency management, pooling, remote or web service invocation ,timers and asynchronous method invokation.
Of course you could also get all aspects using third party libraries - but this would introduce additional complexity to your project. In terms of functionality IMHO EJB are the place to implement :
Business logic, allowing you to have a cleaning separation of busniness logic and web tier logic (implemented by "JSF backing beans" which are CDI managed beans but no EJB)
Functionality which makes most sense for components which are entrypoints to the application (endpoints for remote invocations delivered via RMI or HTTP)
Finally if you need EJB services then you need an Aplication Server (eg. GlassFish or Jboss AS) if you only need CDI services you need a Servlet Container(e.g Tomcat) plus CDI libraries.
Do you need the features provided by EJBs, i.e. security and transaction management? If the answer is yes, EJBs might be a good option.
If the answer is no, and you only need dependency injection, CDI could then be a good option.
You can also get similar capabilities with other 3rd party products, like Spring (dependency injection, Spring security, etc), but deciding whether you use one (EJB) or the other (e.g. Spring) is in many of the cases a matter of previous skillset.
In my opinion, if there are no previous constraints, going Java spec compliant is a good investment.
I would suggest you to start with the CDI and proceed to the EJB's (which is really adding one annotation on top of your POJO) if the requirements needs them (just as it was told - transactionality, web services, JMX, timers, EJB asynchronous invocations).
It's quite reasonable to develop an application in which your entry point is an EJB which encompasses your call in the transaction and allows you to define multiple entry points. The EJB then invokes the CDI beans with the business logic in them.
It's also worth noticing that the TomEE is a certified Java EE 6 Web Profile developed on top of the Apache Tomcat.

For RESTful services in Java, is JAX-RS better than an MVC framework like Swing, Grails or Play?

For example, Play-framework supports RESTful services like this: RESTful on Play! framework
How does this compare to something like Jax-RS Jersey implementation? Does a framework like Play run circles around Jersey because of all it's cool bells and whistles, and it does REST too?
Developer productivity is important, but so is a proper implementation. Perhaps using an MVC framework for REST only services is 'wrong'?
Note, only RESTful services, no UI components at all.
Even though it's not "wrong" to use an MVC framework for RESTful services, there are some pros and cons versus using a JAX-RS implementation.
(Disclaimer: I have only used Jersey and Play! for fun, and not on production-grade systems, so I have tailored my comments more generally to MVC vs. JAX-RS. Keep in mind that these are broad generalizations.)
MVC frameworks--at least the ones that are considered developer friendly and "slick"--typically save you from having to build a persistence layer (the model part). Most also simplify "routing" requests using either scaffolding via convention or some form of configuration. The downsides are that you have to conform to some conventions for your controllers and usually have to write a view for each resource (or build layers of abstractions to avoid rewriting the same code).
JAX-RS excels at defining the routing (using Java annotations) as well as eliminating any restrictions on the service class. In my experience, that has greatly reduced the amount of boilerplate code and developer overhead. Jersey and Apache CXF also handle the XML or JSON serialization using JAXB annotations, which eliminates the need to figure out the view in an MVC context. The downside here is that you have to figure out your own ORM or persistence layer, which could be good or bad depending on whether you're building on top of existing data or creating a greenfield system (or using something other than an JPA/RDBMS e.g. NoSQL data store).
My own personal comment: Play! is a really cool framework, but I'd choose CXF (or Jersey) over an MVC framework any day for building out a RESTful service. In my experience, this frees up the developer to focus on the logic needed for the service, and opens up options for different database approaches. Right tool for the right job.
As a rule of thumb: For Scala, use Play. For Java, use Jersey.
You can use Jersey/Scala and Play/Java; I've done both. It works. It isn't bad. But unless you have a particular reason to do that, I wouldn't mix ecosystems. Java and Scala are interoperable but they have different ecosystems, I would avoid adding Java-isms if you are using Scala or Scala-isms and dependencies if you are running straight Java.
Jersey and Play are generally close for REST services. Neither really has any killer features over the other.
Jersey defines URL mappings in annotations, Play defines them in a service wide route file. And they bundle or have varying quality of integration with different libraries for things like XML, JSON, database, testing, mocking, dependency injection libraries and app server deployment.
The Java world has JMS, Spring, JUnit, jdbi/hibernate/jpa, Jetty/Grizzly. The Scala world has Akka, specs2/ScalaTest, Anorm/slick. Jersey is a better fit for the first world, Scala for the second. You can definitely cross that, but it will be a little less elegant and might require more glue coding.
JAX-RS is a standard and implementations can be created by different vendors. Jersey is one such implementation. The other frameworks may make use of JAX-RS but are not standards. So it is not a one-to-one comparison.
I have never heard of Play before but it does look interesting, more akin to Rails and Django than Jersey. What I like about Jersey is that it can be integrated into existing Java web applications by simply adding the JARs and declaring some things in the web.xml. What I find confusing about Jersey and JAX-RS is the routing.
Play seems to make routing easier, however, correct me if I'm wrong, seems like it is an all-or-nothing framework and cannot be used alongside other servlets in the same web application.