What's the difference between @Singleton and @ApplicationScoped? Confused.
seto Aug 28, 2016 7:10 AMpublic static void main(String[] args) {
CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
cdiContainer.boot();
// Starting the application-context enables use of @ApplicationScoped beans
ContextControl contextControl = cdiContainer.getContextControl();
contextControl.startContext(ApplicationScoped.class);
// You can use CDI here
Kernel k = BeanProvider.getContextualReference(Kernel.class,false);
k.show();
System.out.println(k);
System.out.println(k.nameCache);
k.show();
cdiContainer.shutdown();
}
Here's a simple application with DeltaSpike and Weld. I'm using it in Java SE.
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
// BeanManager beanManager = container.getBeanManager();
// Bean<Kernel> bean = (Bean<Kernel>) beanManager.resolve(beanManager.getBeans(Kernel.class));
// Kernel k = (Kernel) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));
// Kernel k = beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean)); // this will work because it refer to the actual object instead of proxy
Kernel k = container.select(Kernel.class).get();
k.show();
System.out.println(k);
System.out.println(k.nameCache);
k.show();
container.shutdown();
}
Or maybe use this without DeltaSpike, Weld only. The output is the same.
@Inject
@NameCache
Cache<String, String> nameCache;
public void show(){
System.out.println(this);
System.out.println(this.nameCache);
}
Here's the main code of Kernel.
co.kaiba.blueeyes.impl.kernel.Kernel@2432c72c
Cache 'name-cache'@DESKTOP-7SRGBKP-36592
co.kaiba.blueeyes.impl.kernel.Kernel@2432c72c
null
co.kaiba.blueeyes.impl.kernel.Kernel@2432c72c
Cache 'name-cache'@DESKTOP-7SRGBKP-36592
Here's the output of @ApplicationScoped Kernel.
co.kaiba.blueeyes.impl.kernel.Kernel@2121d0ed
Cache 'name-cache'@DESKTOP-7SRGBKP-37141
co.kaiba.blueeyes.impl.kernel.Kernel@2121d0ed
Cache 'name-cache'@DESKTOP-7SRGBKP-37141
co.kaiba.blueeyes.impl.kernel.Kernel@2121d0ed
Cache 'name-cache'@DESKTOP-7SRGBKP-37141
Here's the output of @Singleton Kernel.
The output of k.nameCache is different in this case.
I'd like to know the actual difference between @Singleton and @ApplicationScoped.
The documentation doesn't clearly clarify the difference.
I think the proxy object do the trick.
Then how can I access to the field of proxy object?
Or I can do it only with a getter method?
Why is the injection in the Kernel only correct with show method in @ApplicationScoped?
But why is the injection in the Kernel always correct with @Singleton?
Please clarify it. Thanks.