15.11.18

Ejemplo de uso de @Autowire (Spring framework)

Un ejemplo sencillo. El componente, etiquetado como @Component.

import java.util.stream.IntStream;
import org.springframework.stereotype.Component;

@Component
public class MiComponente
{
    public int sumRange (int i, int j)
    {                
        return IntStream.rangeClosed(Math.min(i,j), Math.max(i,j)).parallel().sum();
    }
}

El controlador:

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
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
    private MiComponente miComponente;

    @PostConstruct
    public void init()
    {
        i=new AtomicInteger(0);
    }

    @RequestMapping("/")
    public String index() {
        int i=this.i.getAndIncrement();
        return "Oh! My gosh! The sum from "+0+" to "+i+" is " + miComponente.sumRange(0,i)+".";
    }
    
}

El componente es creado e inyectado por el contenedor Swing en el controlador.



No hay comentarios :