Spring 2.0 Annotations

Hace tiempo que me he ausentado, pero ha sido en contra de mi voluntad , ya que otros menesteres me han retenido aunque al fin estoy de vuelta y con más fuerza que nunca.

Me ha dado tiempo a leer una noticia que ha hecho que la alegría perle mi faz, Spring tiene annotations para los retractores del XML y para usarlas sólo hace falta la JDK 1.5 y la librería spring.jar.

Sabéis que soy amante de demostrar el movimiento andando así que vamos directamente al grano:

@Bean(name = “test”)
public class TestObject {
public void printName() {
System.out.println(”No Name, just an example”);
}

La anotación únicamente da de alta un bean en el contexto de Spring.

@Bean(name=”main”)
public class Main {
private TestObject test;

/**
* this method should be called from spring to set the variable to the other bean in the context which has the name set to test
* @param test
*/
public void setTest(TestObject test) {
this.test = test;
}

public static void main(String[] args){
TOAnnotationXmlApplicationContext appctx = new TOAnnotationXmlApplicationContext(”classpath*:applicationContext.xml”);
Main m = (Main) appctx.getBean(”main”);
m.test.printName();
}

}
}

En este bean utilizamos la annotation @Bean para dar de alta el bean Main y la annotation @param para inyectarle el bean test. En el main únicamente se accede a la factoría de Spring y se invoca el método printName().

El xml quedaría así:

< beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:tx=”http://www.springframework.org/schema/tx”
xmlns:aop=”http://www.springframework.org/schema/aop”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd”
default-autowire=”byName”>

< /beans>

Como se puede observar el XML ha quedado reducido a su mínima expresión. Eliminar el XML tiene cosas buenas pero también malas al utilizar annotations ligamos la aplicación indefectiblemente al container de Spring lo cual no es nada bueno así lo mejor es utilizar annotations para realizar los prototipos y una vez estos funcionen realizar el prototipo final utilizando el XML para desacoplar al máximo la aplicación. Spring 2.0 tiene soporte para utilizar annotations para realizar aspectos con AspectJ y para realizar transacciones declarativas así que unidas a estas hacen que el que quiera se pueda olvidar del XML definitivamente.

Para el que quiera indagar más la dirección es:

https://spring-annotation.dev.java.net/

Comenta el articulo:

Requerido

Requerido,