You can find the full source code for this website in the Seam package in the directory /examples/wiki. It is licensed under the LGPL.
| Online: | 19 Members of 4546 |
| Forum: Seam Users |
21. Mar 2008, 20:19 CET | Link |
Hi,
How can I inject the applicationContext? I tried
@In private Context applicationContext;
but this doesn't work. Do I have to use Component.getInstance()?
p.s. I don't mean Spring's applicationContext, I mean the application scope (ServletConfig) of the application
The various contexts don't exist in a context themselves. If you want a reference to the application context, simply use Contexts.getApplicationContext().
Thank you, Shane. That worked. Is there any way to inject Contexts.getApplicationContext() into my component?
Or better yet, any way to set values on the application context from components.xml? Something like:
<core:contexts scope="application" name="myProperty" value="true"/>
You can only inject something if it already exists in a context, or if it has a @Factory or if it's an auto-create component. So what you could probably do if you want is create a factory method that returns the application context and annotate it with @Factory(). A bit of a hack, but it would work.
You can't set ad-hoc values in the application context using components.xml, only declare application-scoped components.
I don't know if I'd call it a hack; there's a built in Seam component that does exactly this (org.jboss.seam.core.Contexts). So, Bill's code should run as-is.
Well, you can do something like this, though it's slightly noisy:
<factory name="myProperty" value="#{true}" scope="application" auto-create="true"/>Odd... that should definitely work, and works in a test case I just put together. I'm not sure why it's not working for you.
It's null for me. Can you post your test case?
Hmmm... nothing is getting injected for me.
Have you been able to figure out what's going on?
Sure. Here it is:
package com.example.sandbox; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.contexts.Context; import org.jboss.seam.log.Log; import org.jboss.seam.mock.SeamTest; import org.testng.Assert; import org.testng.annotations.Test; public class ApplicationScopeTest extends SeamTest { @Name("applicationScopeHolder") public static class ApplicationScopeHolder { @Logger Log log; @In Context applicationContext; //specified in components.xml @In boolean testProperty; public void verify() { log.info("verifying applicationContext not null"); Assert.assertNotNull(applicationContext); Assert.assertEquals(testProperty, true); } } @Test public void testApplicationScopeFactory() throws Exception { new ComponentTest() { @Override protected void testComponents() throws Exception { invokeMethod("#{applicationScopeHolder.verify}"); } }.run(); } }(make sure your test src folder has a seam.properties file).