DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Trending

  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Production-Grade RAG: Why Vector Search Isn't Enough (and How Hybrid Search Fills the Gaps)
  • Token Attribution Framework for Agentic AI in CI/CD
  • Reactive Ops to Autonomous Infrastructure: How Agentic AI Is Redefining Modern DevOps
  1. DZone
  2. Coding
  3. Frameworks
  4. What Is a Spring Context?

What Is a Spring Context?

Spring contexts are your tickets to bringing beans to your Java app. Make sure you know how to set up dependencies and incorporate them into your code.

By 
Gaurav Rai Mazra user avatar
Gaurav Rai Mazra
·
Mar. 21, 17 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
140.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will create a Spring context and get a bean object from it.

What Is a Spring Context?

Spring contexts are also called Spring IoC containers, which are responsible for instantiating, configuring, and assembling beans by reading configuration metadata from XML, Java annotations, and/or Java code in the configuration files.

Technologies Used

  • Spring 4.3.6.RELEASE

  • Maven Compiler 3.6.0

  • Java 1.8

We will first create a simple Maven project. You can select maven-archtype-quickstart as the archetype.

Adding POM Dependencies

We will add spring-framework-bom in our dependency management.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.3.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


The benefit of adding this is to manage the version of the added Spring dependencies from one place. With this, you can omit mentioning the version number for Spring dependencies.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <scope>runtime</scope>
</dependency>


Now, we will create a class, GreetingService, which is eligible to be registered as a bean in a Spring context.

@Service
public class GreetingService {
    private static final Logger logger = Logger.getLogger(GreetingService.class.getName());

    public GreetingService() {

    }

    public void greet() {
        logger.info("Gaurav Bytes welcomes you for your first tutorial on Spring!!!");
    }
}


@Service, at the class level, means that this is a service and is eligible to be registered as a bean in the Spring context.

Instantiating a Container

Now, we will create the object of a Spring context. We are using AnnotationConfigApplicationContext as a Spring container. Also, there are other Spring containers like ClassPathXmlApplicationContext, GenericGroovyApplicationContext, etc. which we will discuss in future posts.

ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
      "com.gauravbytes.hellogb.service");


As you see at the time of object construction for AnnotationConfigApplicationContext, I am passing one string parameter. This parameter (of the varags type) is the basePackages , which the Spring context will scan for bean registration.

Now, we will get a bean object by calling getBean() on the Spring context.

GreetingService greetingService = context.getBean(GreetingService.class);
greetingService.greet();


At last, we are closing the Spring container by calling close().

context.close(); 


It is important to close the spring context (container) after use. By closing it, we ensure that it will release all the resources and locks that its implementation might hold and will also destroy all the cached singleton beans.

We have also included maven-compiler-plugin in pom.xml to compile the Java sources with the configured Java version (in our case, it is Java 1.8).

You can also find the example code on GitHub.

Spring Framework

Published at DZone with permission of Gaurav Rai Mazra. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook