Spring.io
-
Upload
cedric-gillet -
Category
Technology
-
view
398 -
download
4
Transcript of Spring.io
SPRING.IO
Let’s meet up
Money, money, money...
merger and Acquisition?
● January 4, 2004 : EMC² acquires VMware
● August 10, 2009 : VMware acquires Springsource
● March 20, 2012 : EMC² acquires Pivotal Labs
● April 1, 2013 : Pivotal Software is created○ All of VMware's applications and
developer-oriented products, including Spring, tc Server, Cloud Foundry, RabbitMQ, GemFire, and SQLFire were transferred to this organization
● October 12, 2015 : Dell Inc announced its intent to acquire EMC² in a cash-and-stock deal valued at $67 billion
Spring Evolution
Some of boring spring release dates● 1.0.0 released in March 2004
● 2.0.0 released in October 2006
● 2.5.0 released in November 2007
● 3.0.0 released in December 2009
● 3.1.0 released in December 2011
● 3.2.5 released in November 2013
● 4.0.0 released in December 2013
● 4.2.0 released in July 2015
At the beginning● Core container
○ the core of IoC pattern
● Beans / Core○ fundamental parts of the
framework○ IoC / Dependency Injection○ BeanFactory
● Context○ Manage Spring context○ I8N○ EJB/JMX ○ caching/mailing/scheduling/
template engine
● SpEL○ Extend unified EL
At the beginning● AOP
○ AOP Alliance-compliant aspect-oriented programming by proxying spring beans
● Aspects○ AspectJ integration
● Instrumentation○ class instrumentation support○ classloader implementation
● Messaging (Spring 4)○ Abstraction for messaging-based
applications○ Annotations for mapping messages
to methods
At the beginning● JDBC
○ JDBC abstraction
● Transactions○ Programmatic and declarative
transaction
● ORM○ Integration layers for ORM (JPA,
JDO, Hibernate)
● OXM○ Abstraction layer Object/XML
mapping (JAXB, Castor, XMLBeans, JiBX, XStream)
● JMS○ Integration with Messaging
At the beginning● Servlet
○ Basic web integration○ Web-oriented application context
● Web○ Spring MVC○ Rest Webservices
● WebSocket○ Abstraction for websocket
integration
● Portlet○ MVC implementation to be used in
a Portlet environment
At the beginning● Test
○ Unit testing / integration testing with JUnit or TestNG
○ Mock spring commons object
○ Consistent loading of Spring ApplicationContexts and caching of those context
And does it make the cofee ?
Spring side projects● Based upon spring framework runtime
● 17 side projects
● Community Projects○ Spring ROO○ Spring Scala
● Pojects in the Attic○ Spring BlaezDS Integration○ Spring Loaded○ Spring Shell○ Rest Shell
Spring DATA● Consitent Spring-based data access
● Main Modules○ Spring Data commons○ Spring Data JPA○ Spring Data MongoDB○ Spring Data Redis○ Spring Data Solr○ Spring Data Gemfire○ Spring Data KeyValue○ Spring Data REST
● Community modules○ Spring Data JDBC Extensions○ Spring for Apache Hadoop
● Interface driven, no more need of implementation
Spring DATApublic interface SimpleUserRepository extends CrudRepository<User, Long> {
User findByTheUsersName(String username);
List<User> findByLastname(String lastname);
@Query("select u from User u where u.firstname = ?")
List<User> findByFirstname(String firstname);
@Query("select u from User u where u.firstname = :name or
u.lastname = :name")
List<User> findByFirstnameOrLastname(@Param("name") String
name);
}
Spring XD● BigData Spring solution
● Data ingestion
● Real time analytics
● Batch processing
● Data export
Spring XD
Spring Batch● Transaction management
● Chunk based processing
● Declarative I/O
● Start / Stop / Restart
● Retry / Skip
● Web based administration interfaces (Spring Batch Admin)
Spring Batch@Configuration@EnableBatchProcessing@EnableAutoConfigurationpublic class BatchConfiguration {
@Autowired private JobBuilderFactory jobBuilderFactory;
@Autowired private StepBuilderFactory stepBuilderFactory;
@Bean public Step step1() { return stepBuilderFactory.get("step1") .tasklet(new Tasklet() {
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext){
return null;}
}).build(); }
@Bean public Job job(Step step1) throws Exception { return jobBuilderFactory.get("job1") .incrementer(new RunIdIncrementer()) .start(step1) .build(); }}
Spring Security● Comprehensive and extensible support
for both Authentication and Authorization
● Protection against attacks like session fixation, clickjacking, cross site request forgery, etc.
● Servlet API integration
● Optional integration with Spring Web MVC
● Much more...
Spring Security
@EnableWebSecuritypublic class SecurityConfig {
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); }}
Spring Integration● Implementation of most of the Entreprise
Integration Patterns○ Endpoint○ Channel (P2P and Publish/Subscribe)○ Aggregator○ Filter○ Transformer○ Control Bus
● Integration with External Systems○ ReST/HTTP○ FTP/SFTP○ Twitter○ Webservices (Soap and ReST)○ TCP/UDP○ JMS○ RabbitMQ○ Email
● Extensive JMX support
Spring Integration@Configuration@SpringBootApplication@IntegrationComponentScanpublic class Application {
public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); TempConverter converter = ctx.getBean(TempConverter.class); System.out.println(converter.fahrenheitToCelcius(68.0f)); ctx.close(); }
@MessagingGateway public interface TempConverter {
@Gateway(requestChannel = "convert.input") float fahrenheitToCelcius(float fahren);
}
@Bean public IntegrationFlow convert() { return f -> f .transform(payload -> "<FahrenheitToCelsius xmlns=\"http://www.w3schools.com/webservices/\">" + "<Fahrenheit>" + payload +"</Fahrenheit>" + "</FahrenheitToCelsius>") .enrichHeaders(h -> h .header(WebServiceHeaders.SOAP_ACTION, "http://www.w3schools.com/webservices/FahrenheitToCelsius")) .handle(new SimpleWebServiceOutboundGateway( "http://www.w3schools.com/webservices/tempconvert.asmx")) .transform(Transformers.xpath("/*[local-name()=\"FahrenheitToCelsiusResponse\"]" + "/*[local-name()=\"FahrenheitToCelsiusResult\"]")); }
}
● Contract-First development
● Loose coupling between contract and impl
● Powerful mappings
● XML Api support
● Support WS-Security
● Integrates with Spring Security
● Low activity in the repository
Spring Web Services
Spring Web Services<beans xmlns="http://www.springframework.org/schema/beans"> <bean id="webServiceClient" class="WebServiceClient"> <property name="defaultUri" value="http://localhost:8080/WebService"/> </bean></beans>
public class WebServiceClient {
private static final String MESSAGE = "<message xmlns=\"http://tempuri.org\">Hello World</message>"; private final WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
public void setDefaultUri(String defaultUri) { webServiceTemplate.setDefaultUri(defaultUri); }
// send to the configured default URI public void simpleSendAndReceive() { StreamSource source = new StreamSource(new StringReader(MESSAGE)); StreamResult result = new StreamResult(System.out); webServiceTemplate.sendSourceAndReceiveToResult(source, result); }
// send to an explicit URI public void customSendAndReceive() { StreamSource source = new StreamSource(new StringReader(MESSAGE)); StreamResult result = new StreamResult(System.out); webServiceTemplate.sendSourceAndReceiveToResult("http://localhost:8080/AnotherWebService", source, result); }}
Spring Web Flow● Allows implementing the “flows” of a
web application
● Clear start and end point
● User must go through a set of screens in a specific order
● Changes not finalized until the last step
Spring Web Flow<?xml version="1.0" encoding="UTF-8"?><flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="
http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow.
xsd">
<view-state id="step1" view="embeddedFlow/step1"><transition on="next" to="step2"/><transition on="cancel" to="cancel"/>
</view-state>
<view-state id="step2" view="embeddedFlow/step2"><transition on="previous" to="step1"/><transition on="finish" to="success"/><transition on="cancel" to="cancel"/>
</view-state>
<end-state id="success" view="embeddedFlow/success"/>
<end-state id="cancel" view="embeddedFlow/cancel"/></flow>
Spring HATEOAS● HATEOAS : Hypermedia as the Engine
of Application State
● Model classes for link, resource representation models
● Link builder API to create links pointing to Spring MVC controller methods
● Support for hypermedia formats like HAL
Spring HATEOASclass BookmarkResource extends ResourceSupport {
private final Bookmark bookmark;
public BookmarkResource(Bookmark bookmark) { String username = bookmark.getAccount().getUsername(); this.bookmark = bookmark; this.add(new Link(bookmark.getUri(), "bookmark-uri")); this.add(linkTo(BookmarkRestController.class, username).withRel("bookmarks")); this.add(linkTo(methodOn(BookmarkRestController.class, username).readBookmark(username, bookmark.getId())).withSelfRel()); }
public Bookmark getBookmark() { return bookmark; }}
Spring LDAP● Provides LDAP template which eliminates
the need to worry about creating and closing LdapContext and looping through NamingEnumeration
● Contains classes for dynamically building LDAP filters and Distinguished Names
● Client-side LDAP transaction management
Spring LDAPLdapQuery query = query()
.base("dc=261consulting,dc=com")
.attributes("cn", "sn")
.where("objectclass").is("person")
.and("sn").is(lastName);
@Entry(objectClasses = { "person", "top" }, base="ou=someOu")public class Person { @Id private Name dn;
@Attribute(name="cn") @DnAttribute(value="cn", index=1) private String fullName;
private String description;
@DnAttribute(value="ou", index=0) @Transient private String company;
@Transient private String someUnmappedField; // ...more attributes below}
Spring Session● API and implementations for managing a
user's session
● HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way○ Clustered Sessions○ Multiple Browser Sessions○ RESTful APIs
● WebSocket - provides the ability to keep the HttpSession alive when receiving WebSocket messages
Spring Session
@EnableRedisHttpSession public class Config {
@Beanpublic JedisConnectionFactory connectionFactory(){
return new JedisConnectionFactory();}
}
MAGIC
Spring Social● Connect your Spring application to
social network
● Main projects○ Facebook○ Twitter○ LinkedIn
● Incubator projects○ Github○ Tripit
● Community Projects (33)○ Dropbox○ Google○ Flickr○ etc...
Spring Social@Beanpublic ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(
environment.getProperty("facebook.clientId"), environment.getProperty("facebook.clientSecret")
)); return registry;}
@Injectprivate Environment environment;
@RequestMapping(value="/", method=RequestMethod.GET)public String home(Model model) {
List<Reference> friends = facebook.friendOperations().getFriends();
model.addAttribute("friends", friends);
return "home";}
Spring AMQP
● Advanced Message Queuing Protocol Spring integration
● Listener container for asynchronous processing of inbound messages
● RabbitTemplate for sending and receiving messages
● RabbitAdmin for automatically declaring queues, exchanges and bindings
Spring AMQPpublic static void main(final String... args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml"); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); template.convertAndSend("Hello, world!"); Thread.sleep(1000); ctx.destroy();}
<rabbit:connection-factory id="connectionFactory" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="myExchange" routing-key="foo.bar"/>
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="myQueue" />
<rabbit:topic-exchange name="myExchange"> <rabbit:bindings> <rabbit:binding queue="myQueue" pattern="foo.*" /> </rabbit:bindings></rabbit:topic-exchange>
<rabbit:listener-container connection-factory="connectionFactory"> <rabbit:listener ref="foo" method="listen" queue-names="myQueue" /></rabbit:listener-container>
public class Foo { public void listen(String foo) { System.out.println(foo); }}
Spring Mobile● A Device resolver abstraction for server-
side detection of mobile and tablet devices
● Site preference management that allows the
user to indicate if he or she prefers a
"normal", "mobile", or "tablet" experience
● A site switcher capable of switching the
user to the most appropriate site
● Device aware view management for organizing
and managing different views for specific
devices
Spring Mobile@Controllerpublic class DeviceDetectionController {
@RequestMapping("/detect-device") public @ResponseBody String detectDevice(Device device) { String deviceType = "unknown"; if (device.isNormal()) { deviceType = "normal"; } else if (device.isMobile()) { deviceType = "mobile"; } else if (device.isTablet()) { deviceType = "tablet"; } return "Hello " + deviceType + " browser!"; }
}
Spring for Android● A Rest Client for Android
● Auth support for accessing secure APIs
// The connection URL String url = "https://ajax.googleapis.com/ajax/" + "services/search/web?v=1.0&q={query}";
// Create a new RestTemplate instanceRestTemplate restTemplate = new RestTemplate();
// Add the String message converterrestTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a StringString result = restTemplate.getForObject(url, String.class, "Android");
Spring Cloud● Tools for developers to quickly
build distributed apps○ Distributed/versioned configuration○ Service registration and discovery`○ Routing○ Service-to-service calls○ Load balancing○ Circuit Breakers○ Global locks○ Leadership election and cluster state○ Distributed messaging
● 16 sub-projects
● Integration with spring boot
Spring Cloud
@Configuration@EnableAutoConfiguration@RestControllerpublic class Application {
@Value("${config.name}") String name = "World";
@RequestMapping("/") public String home() { "Hello " + name; }
public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
@Configuration@EnableAutoConfiguration@EnableDiscoveryClient@EnableConfigServerpublic class ConfigServerApplication {
public static void main(String[] args) {SpringApplication.run(ConfigServerApplication.class, args);
}
}
Spring Boot● Create stand-alone Spring
applications
● Embed Tomcat, Jetty or Undertow directly (make JAR not WAR)
● Provide opinionated 'starter' POMs to simplify your Maven configuration
● Automatically configure Spring whenever possible
● Provide production-ready features such as metrics, health checks and externalized configuration
● Absolutely no code generation and no requirement for XML configuration
Spring Boot@Controller@EnableAutoConfigurationpublic class SampleController {
@RequestMapping("/") @ResponseBody String home() { return "Hello World!"; }
public static void main(String[] args) throws Exception { SpringApplication.run(SampleController.class, args); }}
Spring io platformA consistent set of dependencies to deploy easily spring project
Spring devtooling