Rectangle 27 53

The easiest way to get the application context is:

App
android.app.Application
public class App extends Application {
    public static Context context;

    @Override public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }
}
AndroidManifest.xml
<application>
android:name="your.package.name.App"

Any time you need the application context, just get it from App.context.

Application is always initialized first whether your process runs, whether it's an activity, a service, or something else. You will always have access to the application context.

I saw the exact same approach somewhere and I'm using it to make application context accessible throughout my whole application. But I was not sure, is it the best practice to achieve this? Why accessing the context of application is not supplied as a built-in feature in android SDK?

@AlirezaMirian it is supported. By getApplicationContext() on Context objects. However we have to pass the Context object everywhere.

getApplicationContext as you said is a method of Context class or its sub-classes. But assume you are creating a class that overrides AsyncTask to do some stuff in your application. And you wanna manipulate the UI in onPostExecute for example. Anyway, I think life would be more easier if getApplicationContext were static.

I feel like this should be the accepted answer. Clean & elegant!

Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

android - Getting the Application Context - Stack Overflow

android android-activity service android-context
Rectangle 27 26

In my experience this approach shouldn't be necessary. If you need the context for anything you can usually get it via a call to View.getContext() and using the Context obtained there you can call Context.getApplicationContext() to get the Application context. If you are trying to get the Appication context this from an Activity you can always call Activity.getApplication() which should be able to be passed as the Context needed for a call to SQLiteOpenHelper()

Overall there doesn't seem to be a problem with your approach for this situation, but when dealing with Context just make sure you are not leaking memory anywhere as described on the official Google Android Developers blog

The approach you're suggesting is pretty likely to cause the memory leaks the blog post you link to describes. The context returned by the View object will be for the Activity rather than the Application.

Reto - You are correct, I failed to mention that in order to get the Applciaiton context you need to call getApplciationContext() on the context that you get get from View.getContext() as you said in your answer, I am editing now to include that piece of information. Thank you for pointing it out.

android - Using Application context everywhere? - Stack Overflow

android android-context
Rectangle 27 26

In my experience this approach shouldn't be necessary. If you need the context for anything you can usually get it via a call to View.getContext() and using the Context obtained there you can call Context.getApplicationContext() to get the Application context. If you are trying to get the Appication context this from an Activity you can always call Activity.getApplication() which should be able to be passed as the Context needed for a call to SQLiteOpenHelper()

Overall there doesn't seem to be a problem with your approach for this situation, but when dealing with Context just make sure you are not leaking memory anywhere as described on the official Google Android Developers blog

The approach you're suggesting is pretty likely to cause the memory leaks the blog post you link to describes. The context returned by the View object will be for the Activity rather than the Application.

Reto - You are correct, I failed to mention that in order to get the Applciaiton context you need to call getApplciationContext() on the context that you get get from View.getContext() as you said in your answer, I am editing now to include that piece of information. Thank you for pointing it out.

android - Using Application context everywhere? - Stack Overflow

android android-context
Rectangle 27 42

The majority of apps that want a convenient method to get the application context create their own class which extends android.app.Application.

You can accomplish this by first creating a class in your project like the following:

import android.app.Application;
import android.content.Context;

public class App extends Application {

    private static Application sApplication;

    public static Application getApplication() {
        return sApplication;
    }

    public static Context getContext() {
        return getApplication().getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;
    }
}

Then, in your AndroidManifest you should specify the name of your class in the AndroidManifest.xmls tag:

<application 
    ...
    android:name="com.example.App" >
    ...
</application>

You can then retrieve the application context in any static method using the following:

public static void someMethod() {
    Context context = App.getContext();
}

Before adding something like the above to your project you should consider what the documentation says:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

There is also another way to get the application context using reflection. Reflection is often looked down upon in Android and I personally think this should not be used in production.

To retrieve the application context we must invoke a method on a hidden class (ActivityThread) which has been available since API 1:

There is one more hidden class (AppGlobals) which provides a way to get the application context in a static way. It gets the context using ActivityThread so there really is no difference between the following method and the one posted above:

public static Application getApplicationUsingReflection() throws Exception {
    return (Application) Class.forName("android.app.AppGlobals")
            .getMethod("getInitialApplication").invoke(null, (Object[]) null);
}

Thanks for sharing those two methods that I haven't seen before! (For science!)

Static way to get 'Context' on Android? - Stack Overflow

android android-context
Rectangle 27 42

The majority of apps that want a convenient method to get the application context create their own class which extends android.app.Application.

You can accomplish this by first creating a class in your project like the following:

import android.app.Application;
import android.content.Context;

public class App extends Application {

    private static Application sApplication;

    public static Application getApplication() {
        return sApplication;
    }

    public static Context getContext() {
        return getApplication().getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;
    }
}

Then, in your AndroidManifest you should specify the name of your class in the AndroidManifest.xmls tag:

<application 
    ...
    android:name="com.example.App" >
    ...
</application>

You can then retrieve the application context in any static method using the following:

public static void someMethod() {
    Context context = App.getContext();
}

Before adding something like the above to your project you should consider what the documentation says:

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

There is also another way to get the application context using reflection. Reflection is often looked down upon in Android and I personally think this should not be used in production.

To retrieve the application context we must invoke a method on a hidden class (ActivityThread) which has been available since API 1:

There is one more hidden class (AppGlobals) which provides a way to get the application context in a static way. It gets the context using ActivityThread so there really is no difference between the following method and the one posted above:

public static Application getApplicationUsingReflection() throws Exception {
    return (Application) Class.forName("android.app.AppGlobals")
            .getMethod("getInitialApplication").invoke(null, (Object[]) null);
}

Static way to get 'Context' on Android? - Stack Overflow

android android-context
Rectangle 27 217

The simplest way is to get the application, ApplicationInstance, and use its Context property:

// httpContextBase is of type HttpContextBase
HttpContext context = httpContextBase.ApplicationInstance.Context;

You can, especially if the HttpContextBase instance you've been handed is of type HttpContextWrapper at run-time. The following example illustrates how you can do this. It supposes you have a method called Foo that accepts context as HttpContextBase but then needs to call a method in a third-party assembly (that you may not have the good fortune to modify) that is expecting the context to be typed as HttpContext.

void Foo(HttpContextBase context) 
{
    var app = (HttpApplication) context.GetService(typeof(HttpApplication));
    ThirdParty.Bar.Baz(app.Context);
}

// Somewhere in assembly and namespace ThirdParty,
// in a class called Bar, there is Baz expecting HttpContext:

static void Baz(HttpContext context) { /* ... */ }

HttpContextBase has a method called GetService as a result of supporting IServiceProvider. The GetService override of HttpContextWrapper delegates to the GetService implementation of the wrapped HttpContext instance. The GetService implementation of HttpContext allows you to query for usual suspects like HttpApplication, HttpRequest, HttpResponse and so on. It just so happens that HttpApplication has a property called Context and which returns an instance of HttpContext. So one gets at the wrapped HttpContext instance by asking HttpContextBase for HttpApplication via GetService followed by reading the Context property of the returned HttpApplication instance.

GetService
HttpContext
IServiceProvider.GetService
HttpContextBase

Bear in mind that Foo is no longer testable because it relies on being able to unwrap the underlying HttpContext during testing and which is next to impossible to fake/stub in the first place. The point of this answer, however, is to address the question, How do I get an HttpContext object from HttpContextBase?, literally. The illustrated technique is useful in those situations where you find yourself sandwiched between components you don't necessarily have the luxury to modify.

Very interesting answer, just used it myself in MVC to pass the HttpContext from an Error Filter to ELMAH for logging.

nice answer, bet that took a bit of digging? :)

context.ApplicationInstance.Context

@IshmaelSmyrnow Darn it, don't how I missed that among all the Http*Base variations returned by HttpContextBase. :P I'll update the answer.

How do I get an HttpContext object from HttpContextBase in ASP.NET MVC...

asp.net-mvc httpcontext
Rectangle 27 2

There's a post in Sane Tricks For InsaneWorld blog with an answer. It says you can replace the Application object with your own subclass and then keep the app context statically there. You can find example code in the post.

As of Android Studio 2.2.2, this approach generates a Warning: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run). A static field will leak contexts."

Best way to get an Application Context into a static method in Android...

android android-context
Rectangle 27 2

There's a post in Sane Tricks For InsaneWorld blog with an answer. It says you can replace the Application object with your own subclass and then keep the app context statically there. You can find example code in the post.

As of Android Studio 2.2.2, this approach generates a Warning: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run). A static field will leak contexts."

Best way to get an Application Context into a static method in Android...

android android-context
Rectangle 27 7

  • It's very common that one let spring handle the lifecycle of all the beans, otherwise it might get a bit tricky. The objects that are not spring beans are hopefully initialized somewhere. Make that initializer a spring bean and make it application context aware public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext = null; public static ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void init(){ ServiceBean1 srv1 = (ServiceBean1)applicationContext.getBean("serviceBean1"); myNonSpringObject.setService1(srv1); // Or something } }

Setting up a standalone spring app is very easy. Just create a Spring XML and wire your beans (either via scanning/annotations or XML). It is not really recommended to do this in the main method, but you could easily figure out how to get this setup in your standalone application. Keep in mind that your application itself should not really do much lifecycle logic but let Spring do that.

public class StandaloneSpringApp{
  public static void main(String[] args){
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

    SomeBeanType bean = (SomeBeanType)ctx.getBean("SomeBeanName");
    bean.doProcessing(); // or whatever
  }

}

Your setup makes perfect sense, even though I cannot visualize your entire scope, your approach is a good starting point for a large modularized spring application.

1. In my case, the bean is a business object like ProductBO that is created somewhere using new MyBO(); I'm wondering now, if it's a good idea to call a service from a BO at all, reading different opinions about separation of business logic and business entities. In my understanding Spring is not responsible for creating domain entities or business object, is it?

2. So I wouldn't use my appContext-service.xml and appContext-persistence.xml at all and write a new appContext.xml for batch apps?.

3. Thanks. In fact I'm not sure about the details of my architecture: I have something like a ProductBO that is cached (manually in a ConcurrentHashMap). There is another cache for Producer (a simple entity, that is used in different places in the application). Now ProductBO has a Producer, but because Producers are cached, I didn't want to hard-wire the two, because a producer could be changed (creating a new instance of it, with the same ID). Therefore only the producerID is stored in ProductBO and the Producer loaded from cache on request, using the ProducerService.

java - Spring: how to get hold of Application context in Webapp and St...

java spring spring-mvc architecture
Rectangle 27 7

I will prefer using a singleton class for preference, initialize preference once by application context. create getter and setter(get/put) methods to add, update and delete data.

Also it is good when an application returns from HTTP-request. In this case a context (activity) may not exist, so context.getSharedPreferences will lead to NPE. When using a singleton this won't happen.

android - SharedPreferences application context vs activity context - ...

android sharedpreferences android-context
Rectangle 27 12

Check following Grails FAQ to get access to the application context from sources in src/groovy - http://grails.org/FAQ#Q: How do I get access to the application context from sources in src/groovy?

There is no ApplicationContextHolder class equivalent to ApplicationHolder. To access to a service class called EmailService from a Groovy class in src/groovy, access the Spring bean using:

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA
def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
def emailService = ctx.emailService

While this will allow you to access methods in a service, it will break the services transactionallity. Excerpt from Declarative Transactions: Warning: dependency injection is the only way that declarative transactions work. You will not get a transactional service if you use the new operator such as new BookService()

@ubiquibacon - yes but "def emailService = ctx.emailService" will be a transactional service.I am sorry but what is the issue with accessing service like this?

I don't think that qualifies as "dependency injection". I'll have to do some testing to verify that though.

@ubiquibacon what is the result of the investigation?

Grails 2.x service injection in Groovy/src - Stack Overflow

grails grails-2.0
Rectangle 27 32

Here is an undocumented way to get an Application (which is a Context) from anywhere in the UI thread. It relies on the hidden static method ActivityThread.currentApplication(). It should work at least on Android 4.x.

try {
    final Class<?> activityThreadClass =
            Class.forName("android.app.ActivityThread");
    final Method method = activityThreadClass.getMethod("currentApplication");
    return (Application) method.invoke(null, (Object[]) null);
} catch (final ClassNotFoundException e) {
    // handle exception
} catch (final NoSuchMethodException e) {
    // handle exception
} catch (final IllegalArgumentException e) {
    // handle exception
} catch (final IllegalAccessException e) {
    // handle exception
} catch (final InvocationTargetException e) {
    // handle exception
}

Note that it is possible for this method to return null, e.g. when you call the method outside of the UI thread, or the application is not bound to the thread.

It is still better to use @RohitGhatol's solution if you can change the Application code.

I used the above method KennyTM, but sometimes the method returns null. Is there some other alternative to this ? Like if we get a null here, we can retrieve the context from elsewhere. In my case, onCreate() of Application is not called. But the above method gets called before it. Plzzz help

This will not always work in the case where GC cleaned out all activity related stuff.

Static way to get 'Context' on Android? - Stack Overflow

android android-context
Rectangle 27 32

Here is an undocumented way to get an Application (which is a Context) from anywhere in the UI thread. It relies on the hidden static method ActivityThread.currentApplication(). It should work at least on Android 4.x.

try {
    final Class<?> activityThreadClass =
            Class.forName("android.app.ActivityThread");
    final Method method = activityThreadClass.getMethod("currentApplication");
    return (Application) method.invoke(null, (Object[]) null);
} catch (final ClassNotFoundException e) {
    // handle exception
} catch (final NoSuchMethodException e) {
    // handle exception
} catch (final IllegalArgumentException e) {
    // handle exception
} catch (final IllegalAccessException e) {
    // handle exception
} catch (final InvocationTargetException e) {
    // handle exception
}

Note that it is possible for this method to return null, e.g. when you call the method outside of the UI thread, or the application is not bound to the thread.

It is still better to use @RohitGhatol's solution if you can change the Application code.

I used the above method KennyTM, but sometimes the method returns null. Is there some other alternative to this ? Like if we get a null here, we can retrieve the context from elsewhere. In my case, onCreate() of Application is not called. But the above method gets called before it. Plzzz help

This will not always work in the case where GC cleaned out all activity related stuff.

Static way to get 'Context' on Android? - Stack Overflow

android android-context
Rectangle 27 13

I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyy name="triggers">
    <list>
        <ref bean="simpleTrigger"/>
            </list>
    </property>
    <property name="applicationContextSchedulerContextKey">
        <value>applicationContext</value>
</property>

Then using below code in your job class you can get the applicationContext and get whatever bean you want.

appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");

Hope it helps. You can get more information from Mark Mclaren'sBlog

Thanks, @Rippon! After much trying and failing, I have used a very similar approach that you suggested : I have not used the applicationContextSchedulerContextKey property and application context, but I used the 'code'<property name="schedulerContextAsMap"> <map> <entry key="mailService" value-ref="mailService" /> </map> </property>

inject bean reference into a Quartz job in Spring? - Stack Overflow

spring quartz-scheduler inject
Rectangle 27 13

I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyy name="triggers">
    <list>
        <ref bean="simpleTrigger"/>
            </list>
    </property>
    <property name="applicationContextSchedulerContextKey">
        <value>applicationContext</value>
</property>

Then using below code in your job class you can get the applicationContext and get whatever bean you want.

appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");

Hope it helps. You can get more information from Mark Mclaren'sBlog

Thanks, @Rippon! After much trying and failing, I have used a very similar approach that you suggested : I have not used the applicationContextSchedulerContextKey property and application context, but I used the 'code'<property name="schedulerContextAsMap"> <map> <entry key="mailService" value-ref="mailService" /> </map> </property>

inject bean reference into a Quartz job in Spring? - Stack Overflow

spring quartz-scheduler inject
Rectangle 27 1

Why can't the code in the secondary modules call MainApp.getInstance() to get the application context? Obviously the secondary module is dependent on the main module so I don't see how this is a circular dependency.

If not, then pass the singleton application context from the main module to the secondary modules (either as a parameter in method calls or as a parameter in the constructor of the component in the secondary module. Then you won't have code in the secondary modules calling MainApp.getInstance(). In any case you cannot have another application class as there is only one application class.

android - Get application context from a secondary module - Stack Over...

android android-context
Rectangle 27 5

If you use a web-app there is also another way to access the application context without using singletons by using a servletfilter and a ThreadLocal. In the filter you can access the application context using WebApplicationContextUtils and store either the application context or the needed beans in the TheadLocal.

Caution: if you forget to unset the ThreadLocal you will get nasty problems when trying to undeploy the application! Thus, you should set it and immediately start a try that unsets the ThreadLocal in the finally-part.

Of course, this still uses a singleton: the ThreadLocal. But the actual beans do not need to be anymore. The can even be request-scoped, and this solution also works if you have multiple WARs in an Application with the libaries in the EAR. Still, you might consider this use of ThreadLocal as bad as the use of plain singletons. ;-)

Perhaps Spring already provides a similar solution? I did not find one, but I don't know for sure.

java - Getting Spring Application Context - Stack Overflow

java spring configuration
Rectangle 27 5

If you use a web-app there is also another way to access the application context without using singletons by using a servletfilter and a ThreadLocal. In the filter you can access the application context using WebApplicationContextUtils and store either the application context or the needed beans in the TheadLocal.

Caution: if you forget to unset the ThreadLocal you will get nasty problems when trying to undeploy the application! Thus, you should set it and immediately start a try that unsets the ThreadLocal in the finally-part.

Of course, this still uses a singleton: the ThreadLocal. But the actual beans do not need to be anymore. The can even be request-scoped, and this solution also works if you have multiple WARs in an Application with the libaries in the EAR. Still, you might consider this use of ThreadLocal as bad as the use of plain singletons. ;-)

Perhaps Spring already provides a similar solution? I did not find one, but I don't know for sure.

java - Getting Spring Application Context - Stack Overflow

java spring configuration
Rectangle 27 1

There is only one application context, so you should get the same one. You can have just one constructor that takes a Context, you don't really need two. Or if you wanted to make sure that you are getting the application context, and not, say, an activity one, you can have your constructor take Application as a parameter which is a Context.

android - Getting the Application Context - Stack Overflow

android android-activity service android-context
Rectangle 27 1208

<context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

<context:annotation-config>
<context:component-scan>

Lets start with a basic setup of three beans of type A, B and C, with B and C being injected into A.

package com.xxx;
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc; 
  }
}

With the following XML configuration :

Loading the context produces the following output:

creating bean B: com.xxx.B@c2ff5
creating bean C: com.xxx.C@1e8a1f6
creating bean A: com.yyy.A@1e152c5
setting A.bbb with com.xxx.B@c2ff5
setting A.ccc with com.xxx.C@1e8a1f6

OK, this is the expected output. But this is "old style" Spring. Now we have annotations so lets use those to simplify the XML.

First, lets autowire the bbb and ccc properties on bean A like so:

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

This allows me to remove the following rows from the XML:

<property name="bbb" ref="bBean" />
<property name="ccc" ref="cBean" />
<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A" />
creating bean B: com.xxx.B@5e5a50
creating bean C: com.xxx.C@54a328
creating bean A: com.yyy.A@a3d4cf

Well, annotations are a nice feature but by themselves they do nothing whatsoever. They just annotate stuff. You need a processing tool to find the annotations and do something with them.

<context:annotation-config> to the rescue. This activates the actions for the annotations that it finds on the beans defined in the same application context where itself is defined.

when I load the application context I get the proper result:

creating bean B: com.xxx.B@15663a2
creating bean C: com.xxx.C@cd5f8b
creating bean A: com.yyy.A@157aa53
setting A.bbb with com.xxx.B@15663a2
setting A.ccc with com.xxx.C@cd5f8b

OK, this is nice, but I've removed two rows from the XML and added one. That's not a very big difference. The idea with annotations is that it's supposed to remove the XML.

So let's remove the XML definitions and replace them all with annotations:

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xxx.B;
import com.xxx.C;
@Component
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

While in the XML we only keep this:

<context:annotation-config />

We load the context and the result is... Nothing. No beans are created, no beans are autowired. Nothing!

That's because, as I said in the first paragraph, the <context:annotation-config /> only works on beans registered within the application context. Because I removed the XML configuration for the three beans there is no bean created and <context:annotation-config /> has no "targets" to work on.

But that won't be a problem for <context:component-scan> which can scan a package for "targets" to work on. Let's change the content of the XML config into the following entry:

When I load the context I get the following output:

creating bean B: com.xxx.B@1be0f0a
creating bean C: com.xxx.C@80d1ff

If you look closelly at the classes, class A has package com.yyy but I've specified in the <context:component-scan> to use package com.xxx so this completely missed my A class and only picked up B and C which are on the com.xxx package.

<context:component-scan base-package="com.xxx,com.yyy" />

and now we get the expected result:

creating bean B: com.xxx.B@cd5f8b
creating bean C: com.xxx.C@15ac3c9
creating bean A: com.yyy.A@ec4a87
setting A.bbb with com.xxx.B@cd5f8b
setting A.ccc with com.xxx.C@15ac3c9

And that's it! Now you don't have XML definitions anymore, you have annotations.

As a final example, keeping the annotated classes A, B and C and adding the following to the XML, what will we get after loading the context?

<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />

We still get the correct result:

Even if the bean for class A isn't obtained by scanning, the processing tools are still applied by <context:component-scan> on all beans registered in the application context, even for A which was manually registered in the XML.

But what if we have the following XML, will we get duplicated beans because we've specified both <context:annotation-config /> and <context:component-scan>?

<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />

No, no duplications, We again get the expected result:

That's because both tags register the same processing tools (<context:annotation-config /> can be omitted if <context:component-scan> is specified) but Spring takes care of running them only once.

Even if you register the processing tools yourself multiple times, Spring will still make sure they do their magic only once; this XML:

<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />
<bean id="bla" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla1" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla2" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla3" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

will still generate the following result:

creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@25d2b2
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87

OK, that about raps it up.

I hope this information along with the responses from @Tomasz Nurkiewicz and @Sean Patrick Floyd are all you need to understand how <context:annotation-config> and <context:component-scan> work.

+1 Great answer. Just what I was looking for.

+1 for the great explanation!

Really, amazing explanation. You should use that nice stile of writing of yours and write a book. And I should learn from it.

Quote: " <context:annotation-config /> can be omitted if <context:component-scan> is specified ". Why ever use annotation-config then? Why does it exist?

+1 Very thorough! You should consider writing a tutorial page on Spring!

I wish you wrote the whole Spring manual! Best piece of explanation about anything related to confusing Spring Framework. Thanks.

So simple and outstanding explanation. Beside of getting the answer I also learned good way to tell things :)

java - Difference between vs java spring configuration annotations spring-3