Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • @Scope annotation in Spring

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 434
    Comment on it

    @Scope:- In Spring 3.0 we can define bean or we can do configuration using Java File. @Scope annotation can be used to define the bean scope.

    Example:

    JavaConfig.java

    package com.babita;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Scope;
    
    @Scope("prototype")
    @Configuration
    public class JavaConfig {
        private String message;
    
    
        public String getMessage() {
            return message;
        }
    
    
        public void setMessage(String message) {
            this.message = message;
        }
    }
    

    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);
    
                JavaConfig obj = (JavaConfig) context.getBean("javaConfig");
                obj.setMessage("Hello World From Manish");
    
                System.out.println(obj.getMessage());
                JavaConfig obj1 = (JavaConfig) context.getBean("javaConfig");
                System.out.println(obj1.getMessage());
        }
    
    }
    

    Output:-

    Hello World From MAnish
    null
    

    In above example I have done the configuration using Java File(JavaConfig). The given java configuration file(JavaConfig.java) can be treated as Bean and we can also mention the scope of that bean using @Scope annotation.

 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: