Spring 4.0 Training in Singapore - zekeLabs
seen from United States
seen from United States
seen from United States
seen from Malaysia
seen from Yemen
seen from United States

seen from Canada
seen from United States
seen from Canada

seen from United States

seen from Malaysia
seen from United States

seen from Malaysia

seen from Canada
seen from China

seen from United States
seen from China
seen from China

seen from United States

seen from Malaysia
Spring 4.0 Training in Singapore - zekeLabs
Spring autowiring using @Autowired annotation will inject dependent beans automatically. In the last tutorial, we have learned autowiring through the XML configuration metadata.
Spring autowiring using @Autowired annotation will inject dependent beans automatically. In the last tutorial, we have learned autowiring through the XML configuration metadata.
Definiciones condicionales en Spring
Cuando se utiliza Spring para desarrollar aplicaciones, muchas veces necesitamos cambiar la definición de algún bean en función de una variante. El caso más común que nos podemos encontrar consiste en la definición del dataSource de la BBDD. Como es lógico, la aplicación en producción hará uso de una BBDD Oracle, MySQL o similar, mientras que los tests de integración usarán una BBDD en memoria. ¿Qué alternativas da Spring para hacer esto?
Java config
Una primera aproximación consistiría en utilizar la configuración usando clases Java para determinar el bean que se desea definir.
@Configuration public static class ContextConfig { @Bean public DataSource dataSource() { if (System.getProperty("production") != null) { return getUsingLookup(); } return getEmbeddedDataSource(); } }
@Profile
Antes de Spring 4, también se podía utilizar los denominados profiles. De forma resumida, un profile engloba los beans definidos en él, de modo que esas definiciones sólo se utilizarán en la aplicación si se activa dicho perfil. ¿Cómo podemos definir los perfiles? Pues, como ya Spring nos tiene acostumbrados, existen varias formas:
En XML: Se puede asociar el atributo profile. Por ejemplo:
<beans profile="dev"> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:com/extrema-sistemas/schema.sql"/> <jdbc:script location="classpath:com/extrema-sistemas/test-data.sql"/> </jdbc:embedded-database> </beans> <beans profile="production"> <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/> </beans>
Configuración Java: Usando la anotación @Profile
@Configuration @Profile("dev") public class DevConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScript("classpath:com/extrema-sistemas/schema.sql") .addScript("classpath:com/extrema-sistemas/test-data.sql") .build(); } } @Configuration @Profile("production") public class ProductionConfig { @Bean public DataSource dataSource() { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } }
Por último, sólo quedaría especificar el perfil que deseamos utilizar, que cambia dependiendo del entorno. Por ejemplo, en tests de integración se utilizaría la anotación @ActiveProfiles(profiles="dev"), mientras que en una aplicación en producción puede utilizarse java -Dspring.profiles.active=production, entre otras formas.
@Conditional
En diciembre, una de las características con las que nos sorprendió Spring 4 fue la inclusión de la anotación @Conditional, con la que el framework permite al usuario especificar con mayor detalle si una definición (o conjunto de definiciones) debe incluirse en el ApplicationContext. ¿Cómo? Veámoslo creando nuestra propia anotación @Profile
Primero, creamos una anotación a la que se le especificará el perfil para el que se quiere activar
@Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Conditional(MyProfileCondition.class) public @interface MyProfile { public String value(); }
Luego, creamos la clase que implementará la lógica de la condición:
public class MyProfileCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // recuperar el valor de la anotación MyProfile y aplicar la lógica correspondiente } }
Por último, utilizamos la configuración Java:
@Bean @MyProfile("production") public DataSource dataSource1() { return getUsingLookup(); } @Bean @MyProfile("dev") public DataSource dataSource2() { return getEmbeddedDataSource(); }
Obtenemos así un ejemplo sencillo de cómo podemos crear condiciones más complejas a la hora de añadir definiciones al ApplicationContext gracias a una de las nuevas características de Spring 4.
Para terminar, cabe mencionar que en esta nueva versión de Spring, la funcionalidad ofrecida con @Profile está implementada haciendo uso de @Conditional y su correspondiente clase ProfileCondition.java, tal y como pueden observar aquí
SpringSource's Oliver Gierke talks Spring, Sessions, Music and Combat
SpringSource Engineer Oliver Gierke takes us through his code beginnings, conference sessions and combat methods.
Can you sum up your JAX London sessions in 140 characters? Spring 4 - "An introduction into the next generation of Spring 4. Solutions for today’s and tomorrow’s enterprise developer’s challenges"
Spring Data JPA - "JPA without the boilerplate - all you need for productive data access layers for (not only) relational persistence" Why is the theme of your session important to developers right now? What issues does it tackle? Spring 4: With Spring 4, the next major version of the most successful enterprise Java framework is close to release. It will set the foundation for the next generation of Java applications being developed. But what challenges do application developers face today? Even more important: what do the solutions look like Spring 4 will offer? JPA: JPA is a solid and mature specification to develop persistence layers on top relational databases. The session will introduce the Spring Data JPA project and outline how helps you to even get rid of most of the boilerplate required to implement persistence layers with JPA and even extend those patterns into newer NoSQL data access technologies. What are you most looking forward to at JAX London? It's getting in touch with developers, being peer amongst peers, the hallway conversations, meeting fellow speakers and being able to get great input from awesome sessions. How did you get into coding and how old were you when you first started? It all started off with a Commodore C64 which I got in 4th grade after being addicted to my cousins one for quite a while ago. It shipped with 1000 page instruction manual which I "read" a couple of times, didn't really understand too much of it. I started trying out the code examples. Which area, or specific projects, within the industry are catching your eye at the moment? I think hypermedia based REST web service carry great potential to improve the way we integrate software systems with each other. Support for hypermedia aspects like links and representations, within especially Java web frameworks is still at an early stage. I guess we'll see a lot of progress there in the future. What does the future hold for Java and the JVM? (If you're not from Java land or prefer, what data challenges do we face?) As the amount of data applications have to deal with is growing steadily, we'll have to build solutions to easily cope with it. Fast data is another aspect of this, streaming values can be significant throughout a short period of time but totally irrelevant a second later. We're still lacking tools to be able to easily build solutions for those. An area where Pivotal is seeing great potential, especially with the Spring XD project. What’s the soundtrack to your work? I usually code to a bit of Dave Matthews Band, John Mayer, Wallis Bird or the German Songwriter Clueso. And finally, would you rather fight one horse-sized duck or 100 duck-sized horses? Explain your reasoning. I'll go with the horse sized duck then as I think ducks are delicious, especially if served with red cabbage and dumplings.
Oliver Gierke is engineer at SpringSource, a division of VMware, project lead of the Spring Data JPA, MongoDB and core module and member of the JPA 2.1 expert group. He has been into developing enterprise applications and open source projects for over 6 years now. His working focus is centered around software architecture, Spring and persistence technologies. He is regularly speaking at German and international conferences as well as author of technology articles.