Spring Bean Annotation Example

                            
                                                              Index

1. Bean definition
2. Bean usage
3. Bean class


1. This class define bean using annotation. Bean name is classHelloBean.



package com.example.springexample.javaclass;

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

import com.example.springexample.xml.hello.HelloBean;


@Configuration
public class AppConfig {

    @Bean(name="classHelloBean")
    public HelloBean getHelloBean(){
        return new HelloBean();
    } 
}


2. This class uses bean.


package com.example.springexample.javaclass;

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

import com.example.springexample.xml.hello.HelloBean;

public class App2 {

 
    public static void main(String[] args) {
  
        ApplicationContext context = 
              new AnnotationConfigApplicationContext(AppConfig.class);
        HelloBean bean = (HelloBean) context.getBean("classHelloBean");
  
        bean.setValue("class config bean");
        bean.printValue();
    }

}



3. This is model(bean) class:

package com.example.springexample.xml.hello;

public class HelloBean { 
 
     private String value;

     public void setValue(String value) {
         this.value = value;
     }
 
     public void printValue(){
         System.out.println("value: " + value);
     }
 
}