Wednesday, 7 February 2018

How to use Autowiring using annotations ?



CLASS DEFINITIONS
// base class
public abstract class Shape {
    abstract void draw();
}



@Component
public class Arc extends Shape {
    public void draw() {
        System.out.println("Draw an Arc...");
    }
}


@Component
public class Line extends Shape {
    public void draw() {
        System.out.println("Draw a Line...");
    }

}



@Component
public class Drawing {
    @Autowired
    private Shape arc;

    // Check ByType first, since there is 2 implementation of Shape => arc & line, Then
       It will check ByName and it will find it => Arc class name

    @Autowired
   
private Shape arc1;
    // Check ByType first, since there is 2 implementation of Shape => arc & line, Then
       It will check ByName. It will not find any class arc1 and throw error when creating this bean
    @Autowired
    private Shape line;
    
// Check ByType first, since there is 2 implementation of Shape => arc & line, Then
       It will check ByName and it will find it => Arc class name

    public void drawAll() {
        arc.draw();
        arc1.draw();
        line.draw();
    }
}


// USAGE
ConfigurableApplicationContext ctx = SpringApplication.run(TrainingApplication.class, args);
Drawing drawing = ctx.getBean(Drawing.class);
drawing.drawAll();



USING @Qualifier
You can use @Qualifier annotation to specify the Bean name to inject explicitly.
    @Qualifier("arc")
    @Autowired

    private Shape arc1;
    // It will consult @Qualifier to check the bean name and autowire it ByName



USING @Resource
@Resource can be used in place of @Autowired and @Qualifier (2 annotations)   
    @Resource("name=arc")
    private Shape arc1;
    // Using @Resource, it checks ByType, since there is 2 implementation of Shape => arc & line,
       Then it will consult name given with @Resource and autowire it ByName


No comments:

Post a Comment

Note: only a member of this blog may post a comment.