Spring Bean Injection Using Annotation

                                                            Index

1. Usage of Bean Injection
2. Configuration class
3. Container class
4. Injected class


1. Usage of Bean Injection ( AppAutoWire.java )


package com.example.springexample.autowire;

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

public class AppAutoWire {

     public static void main(String[] args) {
           ApplicationContext context = 
                 new AnnotationConfigApplicationContext(AppConfigAutoWire.class);
  
           FooService service = (FooService) context.getBean("fooService");
  
           service.method();
  
           FooFormatter formatter = context.getBean(FooFormatter.class);
           System.out.println(formatter.format());
    }
}



2. Configuration class ( AppConfigAutoWire.java)

package com.example.springexample.autowire;

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

@Configuration
public class AppConfigAutoWire {

    @Bean
    public FooFormatter fooFormatter(){
         return new FooFormatter("bean 1");
    }

    @Bean
    public FooService fooService(){
        return new FooService();
    }
}



3.Container Class ( FooService.java)

package com.example.springexample.autowire;

import org.springframework.beans.factory.annotation.Autowired;

public class FooService {

    @Autowired
    FooFormatter fooFormatter;
 
    public void method() {
         System.out.println("method, " +fooFormatter.format());
    }

}



4.Injected Class ( FooFormatter.java)


package com.example.springexample.autowire;

import org.springframework.stereotype.Component;

@Component
public class FooFormatter {

    private String param;
 
    public FooFormatter(String param) {
        this.param = param;
    }
 
    public String format(){
        return "FooFormatter " + param;
    }
}