What Exactly Is a Context in Java

What exactly is a Context in Java?

In programming terms, it's the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.

In some API's you see this name back in an interface/class, e.g. Servlet's ServletContext, JSF's FacesContext, Spring's ApplicationContext, Android's Context, JNDI's InitialContext, etc. They all often follow the Facade Pattern which abstracts the environmental details the enduser doesn't need to know about away in a single interface/class.

What is 'Context' on Android?

Putting it simply:

As the name suggests, it's the context of the current state of the application/object. It lets newly-created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity and package/application).

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes).

Typical uses of context:

  • Creating new objects:
    Creating new views, adapters, listeners:

     TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
  • Accessing standard common resources:
    Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

     context.getSystemService(LAYOUT_INFLATER_SERVICE)
    getApplicationContext().getSharedPreferences(*name*, *mode*);
  • Accessing components implicitly:
    Regarding content providers, broadcasts, intent

     getApplicationContext().getContentResolver().query(uri, ...);

Don't understand the concept of a context in Java EE

A context usually refers to the interface used to interact with your runtime environment. This one provides to your program a set of features (like security, request handling, etc...) usually needed by all application running in this kind of domain. Such an environment is generally named container in the java stack (servlet container, ejb one, etc...)

See What exactly is a Context in Java?

The term root can then be used when there are different context set up for a single application with inheritance between them. The one at the root hierarchy (usually holding some general configuration) is the root context .

See JB Nizet answer here : Web-application context/ root application context and transaction manager setup

However in your case the term root has a peculiar signification as it's used for a web container. It refers mainly to the root of the web application path, as there is only one context per web-app we are talking about the context root of a given web-app.

See http://tomcat.apache.org/tomcat-7.0-doc/config/context.html

What is the java Context class used for?

It is part of JNDI, the Java Naming and Directory Interface. This is one of the services that a Java EE container offers.

Applications can lookup things like data sources (for database access) in JNDI. An administrator can define and configure a data source in the administration console of the Java EE container.

The lines of code that you have in your question do exactly that: lookup a DataSource through JNDI, and then get a database connection from the DataSource.

Have a look at, for example, the documentation of Apache Tomcat to see how this works when you would use the Tomcat servlet container: JNDI Resources HOW-TO and JNDI Datasource HOW-TO

application context. What is this?

@feak gives a straight answer about the meaning of ApplicationContext in terms of Spring. In short, it is an object that loads the configuration (usually a XML file annotation based) and then Spring will start managing the beans and its benefits:

  • Beans declared in package
  • Beans declared by annotations
  • Constructor and method autowiring
  • Bean injection
  • Configuration, .properties and .yaml file loading
  • etc

To start an application context, you may use one of the following:

  • Manually load the application context at the beginning of your application. This is done for sample purposes or in standalone applications:

    public class Foo {
    public static void main(String[] args) {
    ApplicationContext context =
    new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
    //use the context as you wish...
    }
    }
  • In case of Java web applications using Spring MVC, the DispatchServlet will load the application context for you, so you only have to create a springapp-servlet.xml file in WEB-INF folder of the application.

Note that an application context is associated to a single configuration (XML based or not). Period.


After understanding this, you could also understand that you can have more than a single application context per application. This is, having two or more ApplicationContexts in the same application. From the last example in the console application, this is easy to check:

public class Foo {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
ApplicationContext context2 =
new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
//use the context as you wish...
}
}

Note that we have two application contexts using the same XML configuration. Can you do this? Yes, you're actually seeing it here. What's the difference, then? The main difference is that Spring beans singleton scopes are singleton per application context, this mean when retrieving a Bar bean that's configured in applicationContext.xml file from context will not be the same as retrieving it from context2, but several retrieves from context will return the same Bar bean instance.

Is this considered a good or bad practice? Neither, it will depend on the problem to be solved (in case of last example, I would say it is a bad practice). Most people would recommend having all your beans configured in a single place (via XML or another) and loaded by a single application context.

What exactly does context mean in context-(in)sensitive analysis?

The word “context” in the question you linked to does not appear to be used to describe a static analysis, so yours is indeed another question. I do not think that that question's answer are “generic”. But they are definitely not the specific answer you are looking for.

A context-sensitive analysis is an interprocedural analysis that considers the calling context when analyzing the target of a function call.

Here is an example of how a context-sensitive analysis might work:

int a,b;

int *x;

void f(void)
{
++*x;
}

int main(){
x = &a;
f();

x = &b;
f();
}

This is not Java, but your question is mostly about context-sensitivity in dataflow analyses, so I hope it won't be too disturbing.

A context-sensitive analyzer analyses f() (at least) twice in this program, because it is called from from call sites. This makes it precise, as the effects of f() are quite different each time. A context-sensitive analysis can infer that a==1 and b is unchanged after the first call, and that both a and b are 1 after the second call. Context-sensitivity also makes the analysis expensive.

A context-insensitive analysis would only analyze f() once, and would typically only produce information of the sort “f() modifies a or b, thus after any call to f(), the contents of both these variables are unknown”.

Where do @Context objects come from

You can write your own injection provider and plug that into Jersey - look at SingletonTypeInjectableProvider and PerRequestTypeInjectableProvider - extend one of these classes (depending on the lifecycle you want for the injectable object) and register your implementation as a provider in your web app.

For example, something like this:

@Provider
public class MyObjectProvider extends SingletonTypeInjectableProvider<Context, MyObject> {
public MyObjectProvider() {
// binds MyObject.class to a single MyObject instance
// i.e. the instance of MyObject created bellow will be injected if you use
// @Context MyObject myObject
super(MyObject.class, new MyObject());
}
}

To include the provider in your web app you have several options:

  1. if your app uses classpath scanning (or package scanning) just make sure the provider is in the right package / on the classpath
  2. or you can simply register it using META-INF/services entry (add META-INF/services/com.sun.jersey.spi.inject.InjectableProvider file having the name of your provider class in it's contents)

what is meant by context in CDI?

The context of a CDI framework is basically a big map of objects*. You can add objects to the context or make the CDI framework create objects from your service classes by using any CDI configuration method (spring xml beans/annotations like @Component/@Service).

Once you have the context you can get objects from it: (Spring: getBean(name))

Now you can configure dependencies between the objects/beans in the context, and the CDI will make sure any object you get from the context will have its dependencies set. This is the dependency injection part.

Non-contextual objects are simply not added to the context and the CDI framework does not know about them. Usually only service classes are part of the CDI context.

* Not really a map though, objects can be accessed by name, by type and other ways. The default is you get the same object each time you ask by the same name (singleton), although you may configure the CDI to create a new object each time you ask (prototype).



Related Topics



Leave a reply



Submit