What is service 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?

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).

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

 TextView tv = new TextView(getContext()); 
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), . );
 context.getSystemService(LAYOUT_INFLATER_SERVICE) 
getApplicationContext().getSharedPreferences(*name*, *mode*);
 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. )

Читайте также:  Include abstract class php

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.

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.
>
>

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 ApplicationContext s 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 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).

Источник

Spring Context

Теги: spring, java, spring context, данные, объединить компоненты в одно приложение, servicedependency, myservice, автоматическое разрешение зависимостей, mainclass, @сonfiguration, @componentscan, spring-аннотации, @service, beans, @autowired, компоненты

SpringDeep_10.06_Site.png

Под словом «Spring» обычно подразумевают просто IoC-контейнер, помогающий структурировать Java-приложения. В действительности под словом «Spring» скрывается целый мир.

IoC-контейнер, это замечательный способ собрать приложение «по кусочкам» из разных компонентов. Spring же предоставляет удобные способы как написания данных «кусочков», так и объединения их в единое приложение. Например, у нас есть два класса.

 
class MyService < private ServiceDependency dependency; public MyService(ServiceDependency dependency) < this.dependency = dependency; >public void usefulWork() < this.dependency.dependentWork(); >>
 
class ServiceDependency < // fields public ServiceDependency() < >public void dependentWork() < // any actions >>

Данные, компоненты уже достаточно неплохо. Наличие же интерфейсов мы для простоты опустим. Самый простой способ объединить эти компоненты в единое приложение – это написать что-то вроде:

Несмотря на простоту, данный код обладает серьёзными недостатками, которые являются критическими для больших проектов. Действительно, в данном примере вполне очевидно, что экземпляр класса ServiceDependency необходимо создавать раньше, чем экземпляр объекта MyService. А в больших проектах таких сервисов и зависимостей может быть столько, что перебор программистом порядка создания объектов занимал бы совсем неприличное время.

Хочется автоматического разрешения зависимостей, и чтобы даже не задумываться о создании объектов. Здесь и приходит на помощь Spring, а если быть точнее, то Spring Context. Модифицируем немного наши классы, добавив так называемые аннотации стереотипов.

 
import org.springframework.stereotype.Service; @Service class MyService < @Service class ServiceDependency < Ну и, конечно, MainClass: @Configuration @ComponentScan public class MainClass < public static void main(String[] args) < ApplicationContext ctx = new AnnotationConfigApplicationContext(MainClass.class); MyService service = ctx.getBean(MyService.class) service.usefulWork(); >>

И всё! Обратите внимание, что здесь не написано ни одно new наших сервисов.

Разберём подробнее

MainClass помечен аннотацией @Сonfiguration, говорящей о том, что в данном классе содержится конфигурация так называемого контекста Spring.

Как ни странно, из конфигурации в данном классе только аннотация @ComponentScan, которая говорит Spring искать все классы, помеченные Spring-аннотациями (в частности аннотациями стереотипов @Service).

Каждый класс помечен аннотацией @Service. Данные аннотация говорит Spring создать экземпляр объекта данного класса и положить его в некоторое множество таких объектов. Такие объекты, собственно, и называются beans, а множество таких объектов, соответственно, называется контекстом.

Ну и в методе main создаётся тот самый контекст: Spring автоматически определит зависимости beans друг с другом (начиная со Spring 4.0 наличие аннотации @Autowired не обязательно, если есть ровно один конструктор) и создаст экземпляры объектов в нужном порядке. Остаётся только получить экземпляр этого объекта и вызвать метод.

Данный пример, разумеется, рассматривает только один из вариантов создания beans в Spring Context. В действительности, возможностей Spring Context гораздо больше.

Есть вопрос? Напишите в комментариях!

Источник

Оцените статью