• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring 3 @Import annotation with JavaConfig Example

April 2, 2015 by javainterviewpoint Leave a Comment

We have already learnt about JavaConfig in Spring 3 Usually, in spring we will split a large XML configuration files into one or more smaller xml files for maintainability and we will finally import it in a common configuration file. @Import annotation does the same functionality for JavaConfig in Spring 3. Let’s take the below XML

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd>

  <import resource="StaffConfig.xml"/>
  <import resource="StudentConfig.xml"/>
</beans>

In Spring 3 JavaConfig we will use @Import to achieve the same functionality.

package com.javainterviewpoint;

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

@Configuration
@Import({StaffConfig.class,StudentConfig.class})
public class SpringConfig 
{
}

Lets now see how to use @Import with JavaConfig in Spring

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.1.1.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar
    spring-context-3.2.9.RELEASE.jar
    spring-expression-3.2.9.RELEASE.jar

  3. Create the Java classes Staff.java, StaffConfig.java, Student.java, StudentConfig.java, SpringConfig.java and Logic.java under  com.javainterviewpoint folder.

Staff.java

Our Staff Class is a simple class with show() method

package com.javainterviewpoint;

public class Staff 
{
    public void show(String message)
    {
        System.out.println(message+" Welcomes you all");
    }
}

StaffConfig.java

The StaffConfig class is the JavaConfig class corresponding to the Staff class

package com.javainterviewpoint;

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

@Configuration
public class StaffConfig 
{
    @Bean(name="staff")
    public Staff getStaff()
    {
        return new Staff();
    }
}

Student.java

Student Class is also similar to our Staff class which also has a show() method called from our Logic class.

package com.javainterviewpoint;

public class Student 
{
    public void show(String message)
    {
        System.out.println(message+" Welcomes you all");
    }
}

StudentConfig.java

The StudentConfig class is the JavaConfig class corresponding to the Student class

package com.javainterviewpoint;

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

@Configuration
public class StudentConfig 
{
    @Bean(name="student")
    public Student getStudent()
    {
        return new Student();
    }
}

SpringConfig.java

The SpringConfig does the import work here, we will use @Import annotation to import the StaffConfig and StudentConfig classes. We will be reading the SpringConfig in our Logic.java to get bean details.

package com.javainterviewpoint;

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

@Configuration
@Import({StaffConfig.class,StudentConfig.class})
public class SpringConfig 
{
}

Logic.java

  • Through AnnotationConfigApplicationContext we will get the context by reading our SpringConfig class
  • Both Staff and Student class instance is obtained by calling the getBean() method over the applicationContext.
  • The parameter passed to the getBean(“staff”) and getBean(“student”) should be the name defined in @Bean annotation @Bean(name=”staff”),@Bean(name=”student”)
package com.javainterviewpoint;

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

public class Logic 
{
    public static void main(String args[])
    {
        //Reading the SpringConfig.xml
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        
        //Get the Staff instance
        Staff staff = (Staff)context.getBean("staff");
        staff.show("Staff Class");
        
        //Get the Student instance
        Student student = (Student)context.getBean("student");
        student.show("Studnet Class");
    }
}

Output

Upon running our Logic class we will get the below output

Staff Class Welcomes you all
Studnet Class Welcomes you all

Other interesting articles which you may like …

  • Autowiring in Spring
  • Spring Autowiring byName Example
  • Spring Autowiring byType Example
  • Spring Autowiring constructor Example
  • How to Instantiate Spring IoC Container
  • How to Create and Configure Beans in the Spring IoC Container
  • Spring Constructor Injection – Resolving Ambiguity
  • How to create Spring Beans Using Spring FactoryBean
  • How to specify Spring Bean Reference and Spring Inner Bean
  • Spring Dependency Checking and Spring @Required Annotation
  • @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Static Factory Method & Instance Factory Method
  • Spring PropertyPlaceholderConfigurer Example
  • Spring JdbcTemplate Example + JdbcDaoSupport
  • Spring CRUD Example with JdbcTemplate + Maven + Oracle
  • How to lazy initialize Spring beans?
  • How to change Spring Context Configuration file name

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: @Import, JavaConfig, Spring 3

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2022 · Java Interview Point - All Rights Are Reserved ·