Beans

Spring 3 Java Config @Import Example

In this example we shall show you how to use Spring 3.2.3 Java Configuration, and specifically the @Import annotation. Using Java Configuation, we can define beans and configure Spring without using XML configuration files. In particular, @Configuration annotated classes consist of @Bean annotated methods that define instantiation, configuration, and initialization logic for objects to be managed by the Spring IoC container.

The @Import annotation allows loading @Bean definitions from one @Configuration class to another. This approach simplifies container instantiation, as only one class needs to be dealt with, rather than requiring the developer to remember a potentially large number of @Configuration classes during construction.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.

Let’s begin.

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:
 
pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Add cglib dependency.

The cglib library is needed in order to use the @Configuration annotation. It is added to the pom.xml file, as shown below:
 
pom.xml:

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>3.0</version>
		</dependency>

4. Create two simple Spring beans.

HelloWorldService.java:

package com.javacodegeeks.snippets.enterprise.services;


public class HelloWorldService {
	
	public void sayHello(String name) {
		System.out.println("Hello from Java Configuration. " + name);
	}

}

GoodbyeService.java:

package com.javacodegeeks.snippets.enterprise.services;

public class GoodbyeService {

	public void sayGoodbye(String name){
		System.out.println("Goodbye from Java Configuration. "+ name);
	}
}

5. Create the Java Configuration classes for the beans.

The classes are annotated with @Configuration annotation, that indicates that they can be used by the Spring IoC container as sources of bean definitions.
 
HelloConfig.java:

package com.javacodegeeks.snippets.enterprise;

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

import com.javacodegeeks.snippets.enterprise.services.HelloWorldService;
 
@Configuration
public class HelloConfig {
 
    @Bean(name="helloWorldBean")
    public HelloWorldService helloWorldService() {
        return new HelloWorldService();
    }
 
}

GoodbyeConfig.java:

package com.javacodegeeks.snippets.enterprise;

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

import com.javacodegeeks.snippets.enterprise.services.GoodbyeService;
 
@Configuration
public class GoodbyeConfig {
 
    @Bean(name="goodbyeBean")
    public GoodbyeService goodByeService() {
        return new GoodbyeService();
    }
 
}

The @Bean annotation over the methods indicates that they produce beans to be managed by the Spring container.

6. Use @Import annotation.

The @Import annotation is used to load the two configuration classes in one class.

AppConfig.java:

package com.javacodegeeks.snippets.enterprise;

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

@Configuration
@Import({HelloConfig.class, GoodbyeConfig.class})
public class AppConfig {
   
}

6. Run the application.

The AppConfig class is loaded with the AnnotationConfigApplicationContext.
 
App.java:

package com.javacodegeeks.snippets.enterprise;


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

import com.javacodegeeks.snippets.enterprise.services.GoodbyeService;
import com.javacodegeeks.snippets.enterprise.services.HelloWorldService;

public class App {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {

	ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

	HelloWorldService hello = (HelloWorldService) context.getBean("helloWorldBean");
	hello.sayHello("Spring 3.2.3");
	
	GoodbyeService bye = (GoodbyeService) context.getBean("goodbyeBean");
	bye.sayGoodbye("Spring 3.2.3");

	}
}

Alternatively, each bean can be defined in its own xml configuration file, and then the files can be imported in one configuration file, as shown below:
 
hello.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="helloWorldBean"
		class="com.javacodegeeks.snippets.enterprise.services.HelloWorldService">
	</bean>

</beans>

 
goodbye.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="goodbyeBean"
		class="com.javacodegeeks.snippets.enterprise.services.GoodbyeService">
	</bean>

</beans>

 
applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
 
		<import resource="classpath*:config/hello.xml"/>
        <import resource="classpath*:config/goodbye.xml"/>
       
</beans>

The applicationContext.xml is loaded to App2 class, using ClassPathXmlApplicationContext.
 
App2.java:

package com.javacodegeeks.snippets.enterprise;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javacodegeeks.snippets.enterprise.services.GoodbyeService;
import com.javacodegeeks.snippets.enterprise.services.HelloWorldService;

public class App2 {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {

	ApplicationContext context = new ClassPathXmlApplicationContext(
			"applicationContext.xml");

	HelloWorldService hello = (HelloWorldService) context.getBean("helloWorldBean");
	hello.sayHello("Spring 3.2.3");
	
	GoodbyeService bye = (GoodbyeService) context.getBean("goodbyeBean");
	bye.sayGoodbye("Spring 3.2.3");

	}
}

8. Output.

When you execute the application you should see something like the output presented below:

Hello from Java Configuration. Spring 3.2.3
Goodbye from Java Configuration. Spring 3.2.3

 
Download the Eclipse project of this part : springexample.zip
 
This was an example of how to use @Import annotation in Spring Java Configuration class.

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
sukanya
sukanya
6 years ago

It would be helpful if you explain the difference between @Service, @Configuration as well

Back to top button