Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Instantiating the Spring container using AnnotationConfigApplicationContext

    • 0
    • 1
    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 919
    Comment on it

    In Spring 3 we can also create a bean using java file instead of XML.It is alternate way to create the bean, you can also use xml based configuration.

    HelloWorld.java

    package com.babita;
    
    public class  HelloWorld {
    
    
        public void printMessage(String message)
        {
            System.out.println("Hello World From "+message);
        }
    
    }
    

    JavaConfig.java

    package com.babita;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class JavaConfig {
    
        @Bean(name="helloBean")
        public HelloWorld helloWorld() {
            return new HelloWorld();
        }
    
    }
    

    Now define the below class to run the code:

    MainApp.java

    package com.babita;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainApp {
    
    public static void main(String[] args) 
    {
    ApplicationContext context = new                                                 AnnotationConfigApplicationContext(JavaConfig.class);
    
             HelloWorld obj = (HelloWorld) context.getBean("helloBean");
             obj.printMessage("Spring 3.0");
    
        }
    }
    

    In above Example we can see that the JavaConfig.java file can put @Configuration annotation to indicate that is core spring configuration file and @Bean annotation defines the name of bean and finally we can load the JavaConfig.java class via AnnotationConfigApplicationContext to instantiate the bean.

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: