15.11.18

Ejemplo de uso de @Qualifier (Spring framework)

Un ejemplo sencillo del uso de @Qualifier en Spring Framework. Una interfaz:
public interface Operacion
{
    public void establecerValorA (int a);
    public void establecerValorB (int b);
    public double realizarCalculo();    
}
Dos clases que implementan dicha interfaz:
import java.util.stream.IntStream;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("sumarRango")
public class OperacionSumarRango implements Operacion {

    private int a;
    private int b;

    @Override
    public void establecerValorA(int a) {
        this.a=a;
    }

    @Override
    public void establecerValorB(int b) {
        this.b=b;
    }

    @Override
    public double realizarCalculo() {
        return IntStream.rangeClosed(Math.min(a,b), Math.max(a,b)).parallel().sum();
    }
}
import java.util.stream.IntStream;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("sumarPares")
public class OperacionSumarPares implements Operacion {
    private int a;
    private int b;

    @Override
    public void establecerValorA(int a) {
        this.a=a;
    }

    @Override
    public void establecerValorB(int b) {
        this.b=b;
    }

    @Override
    public double realizarCalculo() {
        return IntStream.rangeClosed(Math.min(a,b), Math.max(a,b)).parallel().filter(n->n%2==0).sum();
    }
}
Y el controlador:
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
public class HelloController {
    
    AtomicInteger i;

    @Autowired
    @Qualifier("sumarRango")
    private Operacion op1;

    @Autowired
    @Qualifier("sumarPares")
    private Operacion op2;

    @PostConstruct
    public void init()
    {
        i=new AtomicInteger(0);
        op1.establecerValorA(0);
        op2.establecerValorA(0);
    }

    @RequestMapping("/")
    public String[] index() {
        int i=this.i.getAndIncrement();
        op1.establecerValorB(i);
        op2.establecerValorB(i);
        String[] results=new String[2];
        results[0]="The sum from "+0+" to "+i+" is " + op1.realizarCalculo()+".";
        results[1]="The sum of even numbers from "+0+" to "+i+" is " + op2.realizarCalculo()+".";
        return results;
    }    
}
Y esto es todo.

No hay comentarios :