users@glassfish.java.net

Re: [Asking]About HK2 Construtor Injection

From: John Wells <john.wells_at_oracle.com>
Date: Thu, 28 Feb 2013 08:35:14 -0500

On 2/27/2013 8:59 AM, Tang Yong wrote:
> Hi JWells,
>
> Thanks your reply very much!
>
>> @Inject
>> public LocalServerPoolFactory(TemplateRepository
>> templateRepository,
>> Domain domain,
>> ServerContext environment) {
>> this.templateRepository = templateRepository;
>> this.domain = domain;
>> this.environment = environment;
>> }
> I want to ask whether the above injection way is the same as the
> following(field injection):
>
> @Inject
> TemplateRepository templateRepository;
>
> @Inject
> Domain domain;
>
> @Inject
> ServerContext environment;
>
> public LocalServerPoolFactory() {}

It is *almost* exactly the same except for the fact that you cannot use
"final" for the variables when you inject this way. With constructor
injection you can do this:

private final TemplateRepository templateRepository;
private final Domain domain;
private final ServerContext environment;

@Inject
public LocalServerPoolFactory(TemplateRepository
                                      templateRepository,
                              Domain domain,
                              ServerContext environment) {
        this.templateRepository = templateRepository;
        this.domain = domain;
        this.environment = environment;
}

Other than that they are essentially the same.

>
> Thanks
> --Tang
>
> John Wells wrote:
>> Yes, the standard @Inject is not allowed on parameters, so you would
>> have to change your constructor to look like this:
>>
>> @Inject
>> public LocalServerPoolFactory(TemplateRepository
>> templateRepository,
>> Domain domain,
>> ServerContext environment) {
>> this.templateRepository = templateRepository;
>> this.domain = domain;
>> this.environment = environment;
>> }
>>
>>
>>
>> On 2/27/2013 8:32 AM, Tang Yong wrote:
>>> Hi Jwells, Team
>>>
>>> I have another question about HK2 Construtor Injection.
>>>
>>> Currently, because of a fact that org.jvnet.hk2.annotations.Inject has
>>> been changed into javax.inject.Inject(JSR330 spec), the following
>>> Construtor Injection seemed to have problem,
>>>
>>> public LocalServerPoolFactory(@Inject TemplateRepository
>>> templateRepository,
>>> @Inject Domain domain,
>>> @Inject ServerContext environment) {
>>> this.templateRepository = templateRepository;
>>> this.domain = domain;
>>> this.environment = environment;
>>> }
>>>
>>> In constructor, @Inject seemed to be not allowed there.
>>>
>>> So, I want to know whether there are something with me?
>>>
>>> Thanks
>>> --Tang
>>>
>>
>>