Your First Spring Program Using Java Configuration

We will create a simple class, configure it and test it. You can configure a Spring application through xml, or Java configuration or annotations along with xml or java configuration. In this example, we will see java configuration approach. We will have a Java class annotated with @Configuration to hold bean configuration.

 

Prerequisites

If you are using Maven, just copy paste below dependency into your pom file and all other required dependencies will be added automatically, as they are the transitive dependencies for below dependency.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.6.RELEASE</version>
    </dependency>
</dependencies>

Please use the latest version as available in the Spring website @ http://projects.spring.io/spring-framework.

PS: There is a separate note for getting started with Gradle build, but notes in this section will be using Maven build tool in general. If you are manually adding jars to classpath, you should have already downloaded the spring jars and commons logging jar as described in downloading-and-setting-up-the-spring-framework and added to classpath. We however prefer using a build tool like Maven/Gradle.

 

Bean component class

JJWriter.java

package com.javajee.spring;

public class JJWriter {
    public void write() {
        System.out.println("Default Writer");
    }
}

 

Config class

Our config class will look as below.

DemoConfig.java

package com.javajee.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DemoConfig {

    @Bean (name = "jjwriter")
    public JJWriter getJJWriter()
    {
        return new JJWriter();
    }
}

 

Test Class

The test class will look as below:

JJWriterWithConfigMain.java

package com.javajee.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class JJWriterWithConfigMain {

    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);

        JJWriter writer = context.getBean("jjwriter", JJWriter.class);

        writer.write();

    }

}

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!