Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using CDI in Java is the default constructor necessary?

I'm looking into the code-base of an open source project, mamute which uses CDI. In most classes there is a deprecated no-arg constructor and a constructor annotated @Inject.This is an example class in the mentioned project which has used this approach. So my question is, do we have to have a no-arg constructor even if we have a constructor annotated @Inject?

like image 549
Can't Tell Avatar asked Jul 27 '14 03:07

Can't Tell


1 Answers

The linked class has the following imports and annotations:

import br.com.caelum.vraptor.Controller;
...
import br.com.caelum.vraptor.routes.annotation.Routed;
...

@Routed
@Controller
public class QuestionController {
    ...
}

I've found this javadoc for the Controller annotation.

@Target(value=TYPE)
 @Documented
 @Retention(value=RUNTIME)
 @Stereotype
 @RequestScoped
public @interface Controller

Note the @RequestScoped annotation here.

The request scope is a normal scope (as well as application, session and conversation scopes) and JBoss Weld uses client proxies for normal scoped beans. To be able to create proxies Weld needs the following:

The following Java types cannot be proxied by the container:

  • classes which don't have a non-private constructor with no parameters, and
  • ...

Source: Weld - CDI Reference Implementation, 4.9. Client proxies

In other cases you don't need the no-arg default constructor (see @Singleton beans).

Further links:

  • CDI specification, 6.3. Normal scopes and pseudo-scopes
  • AS7-5089: ApplicationScoped Object is instantiated twice
like image 59
palacsint Avatar answered Nov 15 '22 04:11

palacsint