Pokazywanie postów oznaczonych etykietą spring. Pokaż wszystkie posty
Pokazywanie postów oznaczonych etykietą spring. Pokaż wszystkie posty

piątek, 3 listopada 2017

Spring framework 5 - new & noteworthy

Spring platform


Seems that nowadays everybody at least know (and most use) Spring framework. Well, no wonder. Years ago Spring pioneered lightweight DI container for masses. Later on provided nice (and also lightweight) MVC implementation that could easily play along multiple View (UI) technologies (JSP, vanilla JS, Portlets? you name it). With each and every modern (sometimes only trendy) solution / approach they were ready (REST, polyglot persistence etc.). Apart from the main Spring Framework, there are also additional Spring projects - for example fantastic microservice-enabling Spring Boot.

Spring framework 5


Current newest and shiniest version (actually 5.0.1, reference available here) has been the first major release since December 2013. This means 2,5 years of development, quite a lot I'd say in modern fast-changing software development world. So, what are the most interesting parts of the release?

Reactive Programming


Biggest star of the show - Spring-native reactive programming (go ahead and read Reactive Manifesto if you're not familiar with whole "reactive" hype). Based upon industry-agreed specification which is called Reactive Streams (specification here). Current Java 9 implements Reactive Streams natively, but as Spring 5 is coupled with Java 8, it uses an external implementation of the API - Project Reactor (click here for more info).
The reactive module is called WebFlux. Nevertheless, Spring MVC (REST-style) is still of course supported. Nice comparison in 5 use cases of "new fancy" versus "old proven" can be found here: https://www.infoq.com/presentations/servlet-reactive-stack
In order to make an application fully reactive, it has to use non-blocking model thru all layers, down to persistence. This means that currently it will work only with Mongo, Redis etc. Unfortunately, JPA / JBDC are still inherently blocking :( This can be worked around by separating persistence layer with a queue / working thread, reading / publishing persistence events (Event Sourcing anyone? :-P ).

Core and container changes


Apart from WebFlux, 5.x brings some core enhancements. Among most notable ones is utilisation of Java 8 features. For example, core Spring interfaces have now default method implementations. It means that in many cases you won't need to extends "adapters" implementing the interfaces but simply use them directly. There are also multiple lambdas and streams all around. For example, one can now register beans using a lambda (aka "supplier").  Last but not least, reflection enhancements (for details see here: https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/enhancements.html) are now used for better/faster parameters access.
There is also a nice enhancement for large application start-up. Instead of a time-consuming classpath scanning, applications can now provide an index of candidates in the form of META-INF/spring.components file. Of course the file should be created by a plugin during build (not manually for God sake! :-) ). This should bring noticeable benefits for applications with more than 200 classes. According to the source (JIRA: https://jira.spring.io/browse/SPR-11890), 200 components / 5000 irrelevant classes starts 10% faster. Not that bad at all.

Others

  • Junit 5 fully supported, also on the "integration" side of testing
  • guava (among others) support discontinued :-( 
  • Java 8  / Java EE 7 as a minimum requirement

Further reading

Summary


To sum up, Reactive programming seems to be the main theme of the release. Rest of the updates are rather "sugar" like. It's not bad though, as we should remember to always "leave well alone" :-)

wtorek, 25 lipca 2017

[memo] hibernate's import.sql

There is a neat, heavily undocumented feature oh Hibernate - import.sql.

If Hibernate creates DB schema from scratch - "hibernate.hbm2ddl.auto" is set to either "create" or "create-drop", it will load "import.sql" file located in the root classpath. If Spring Boot is used, the property controlling the behaviour is "spring.jpa.hibernate.ddl-auto".

But why would anyone like to import some static data in a webapp? Well, for prototyping purposes for example. Or for "static" webapp mocking some external resources for integration testing. 

środa, 31 maja 2017

GeeCon part two

A little late (almost two weeks!) but finally completed. Second day of GeeCon (https://www.geecon.org/). How was it? Continue reading to find out.

Improving Java EE with reactive - Ondrej Mihalyi

The presenter started with an outlook of what "reactive" in terms of a web application really means. The idea he focused on was that in order to improve the latency, execution of a request should not block - never, even on I/O. Also, in order to utilise the resources (CPU) as efficiently as possible, there should be ideally as many threads running as there are cores in the system. In a typical, J2EE based application, there goals are impossible to achieve, as each request is served completely by a separate thread which blocks if there is eg a dependent service or a DB call. There are however libraries that can help to make such application more "reactive". In his demo application ("cargo"), Ondrej showed how to use built-in Java 8 CompletableFuture or external RxJava (https://github.com/ReactiveX/RxJava) observables in order to avoid blocking the execution thread. He also mentioned (although he was short on time) that the UI part should be improved as well by using technologies like WebSockets or CDI events.
Whole presentation was quite good content-wise. It was nice to learn how a performance can be improved in an existing application by refactoring it to use some "reactive" stuff. The presenter could improve a bit on a technical side. Keeping an eye on the clock and minimising "live coding" favouring ready, refactored examples would make whole presentation better from reception point of view.

Reactive Spring - Josh Long 

START. DOT SPRING. DOT IO. I could write that this was the second "reactive" presentation, taking on the topic from new Spring library perspective. But no, this was not an ordinary presentation. This was a show. A Josh show. The topic itseflf is very interesting and the Spring implementations are interesting (and impressive) as well. Reactive versions of repositories (Mongo DB implementation here), Reactive Streams (Subscriber, Publisher, Processor) and Reactor (Flux, Mono) concepts, Web Sockets or Server Sent Events for publishing. They even have (in the upcoming release) a reactive, non-blocking security! I had however a strong impression that Josh would be able to make an interesting and involving presentation on any topic... even PHP ;-) Besides strong interest in the Spring reactive what took out of the presentation is - START. DOT SPRING. DOT IO! :-D

Microservices - stages of maturity - Jarosław Pałka / Jakub Marchwicki

The multi-threaded presentation run on two cores in parallel ;-) It was a mixed one - a bit about the main topic (microservices), a bit about a working in a tech organisation. The microservices-oriented part dealt a bit with such principles as being event-driven (publish, publish, publish!) and asynchronous, even in terms of application logging. Also, the Customer Driven Contracts for better APIs were mentioned. The message from the presenters here was that many of the microservices world ideas can be applied to the world of monoliths. The organisation-oriented part was, from my point of view, much more interesting. Jarek and Jakub said many things that may seem obvious, but need to be stated aloud from time to time, just to remind everyone about them. Amon others, the words of wisdom I remembered from the presentation were:
- legacy products - usually nobody to work with these, but usually these are the ones that bring MONEY!
- 3rd Newtonian law of management - if you push people, they will push back even harder
- ignoring the infrastructure is a wide road to failure
- developers should be assigned responsibilities, not roles
- during development focus should be on building a resilient system, not a perfect one
- in general, it's better to fix what's failing than on blaming others (famous "witch hunt")
- never ever do any manual changes on production - if you need to, your product is crap ;-)
Overall, I liked the presentation, especially that my work experience results in similar conclusions as voiced by Jarek and Jakub.

Consumer-Driven Contracts to enable API evolution - Marcin Grzejszczak

Consumer-Driven Contracts is the pattern to enable service evolution, as described by Martin Fowler (https://martinfowler.com/articles/consumerDrivenContracts.html). In his presentation Marcin focused on how CDC can be enabled for a web application using Spring project called Spring Cloud Contract (http://cloud.spring.io/spring-cloud-contract/spring-cloud-contract.html). The idea behind is quite simple - allow writing Contract on an API using a statically typed Groovy DSL, that can be later on automagically converted into stubs used for (client) intergration testing (in a most hyped microservices architecture ;) ). As an added bonus, the same tool will generate (server) acceptance tests out of the same Contracts.
To make long story short - easier decoupling of services for testing and less boilerplate code provided by one nice tool. I like that! :-)


To sum up - this year's edition of GeeCon was both entertaining and educational. I learned few new things, I met some friends from good old days, I ate some cookies. One of the most important aspects for me was an opportunity to see how different things are done in different companies. Having a broader overview is never a bad thing!

piątek, 5 maja 2017

[memo] Accessing files in a web application

Sometimes the easiest things are also the easiest to miss (or to forget :-) ). Therefore, in order to have this once and for all in one place - the quickest guide how to access files in a servlet environment (Spring Boot application in my case).

1. Classpath resource

A file that is present in a classpath (typically /WEB-INF/classes, /WEB-INF/lib).
Can be anything, most probably a configuration file that is packed with WAR during package preparation stage. In case of good old Maven - all of the resources (by default src/main/resources) will end up in the classpath. Access - via context class loader.
For example:

2. Web resource 

All of the web application files - including static content (images, styles, html, ...) and files that are loaded into classpath (JARs from /WEB-INF/lib etc.) can be accessed this way. The only requirement is the presence of a ServletContext. 
PRO TIP: In a Spring application, the ServletContext can be simply autowired into a service requiring it. 
For example: 
As a last word - be __very__ cautious when planning to use ServletContext.getRealPath(). Why? Just take a look here: http://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it

czwartek, 14 sierpnia 2008

Wicket and Spring

Sometime ago I was evaluating Wicket usefulness in development of lightweight, AJAX enabled UIs for web applications. Apache Wicket is modern framework for creating web UIs, well known for its original features as HTML/Java pages implementing separation between page view and logic. Other unique feature is global Application object, usually containing business logic entry points.


Wide range of modern applications requires complex, multi-tier backend (logic and storage, possibly remote, wired together with Web Services) and quite simple frontend (with few user actions available). Server part of the backend, along with WS clients is typically developed with Spring. As far as frontend is concerned, Wicket could be the solution to use.


There are many great Wicket manuals and tutorials, so I won't post any Wicket code here. Those interested can just take a look at Wicket Examples :) Other aspect is Wicket-Spring integration. After some research I decided to go with "central point" solution. This integration type assumes that all logic entry points (usually managers and DAOs) should be injected into Application object. Therefore all Pages have convenient access to the logic. This is compromise between annotations (performing all work under cover, without developer knowledge) and using no dependency injection at all. Because Application object is global (and singleton) it reminds somewhat hated Resource Locator solution, but for the sake of simplicity (remember, be agile..) I can accept it.


Required web.xml configuration is as follows:

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>wicket.wicket-demo</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationFactoryClassName</param-name>
<param-value>
org.apache.wicket.spring.SpringWebApplicationFactory
</param-value>
</init-param>
</filter>

With above entries in webapp config, developer is able to inject logic beans to the Applciation object without problems, as in following example:

<bean id="mrDaoBean"
class="apps.WicketMountains.data.MountainRecordDao">
<property name="sessionFactory">
<ref bean="sessionFactoryBean"/>
</property>
</bean>
<bean id="mrManagerBean"
class="apps.WicketMountains.data.MountainRecordManager">
<property name="mrDao" ref="mrDaoBean"/>
</bean>

<!-- setup wicket application -->
<bean id="wicketApplication"
class="apps.WicketMountains.WicketApplication">
<property name="mrManager" ref="mrManagerBean"/>
</bean>

Wicket components can access logic beans using code similar to call:

((WicketApplication)Application.get()).getMountainRecordManager()

One nice feature of the Wicket framework is bunch of ready to use AJAX components with exhaustive description of use. Beginner in Wicket (as myself) is able to develop first useful, pretty, AJAX enabled webapp in few hours only.

czwartek, 7 sierpnia 2008

HSQL: follow-up

It appears that sometimes one would like to use lightweight HSQL for unit / integration testing of his (hers) Spring-aware application. Nothing simpler ;-)
First thing is preparing Spring bean able to manage lifecycle of an instance of the HSQL database. This could be written by hand, but fortunately convenient class is already available in the Springmodules project. Bean implementation is to be found here.
Second thing is Spring XML configuration of the bean. My sample code is as follows:

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="org.hsqldb.jdbcDriver"/>
<property name="url"
value="jdbc:hsqldb:hsql://localhost/test"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
<property name="defaultAutoCommit" value="true"/>
</bean>

<bean id="dataBase"
class="springmodules.HsqlServerBean"
singleton="true" lazy-init="false">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="serverProperties">
<props>
<prop key="server.port">9001</prop>
<prop key="server.database.0">
file:webapps/SampleApp/db/test</prop>
<prop key="server.dbname.0">test</prop>
</props>
</property>
</bean>

Configuration is pretty straight-forward. Note that we're using DataSource referring to the database configuration. This is done because:
a) Spring bean requires DataSource to commence db shutdown when container goes down
b) helps encapsulating database properties in one entity
The latter can be used more when Hibernate is also in the game. SessionFactory can be configured to use the DataSource with such code as:

<bean id="sessionFactoryBean" class=
"org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml"/>
<property name="dataSource" >
<ref bean="dataSource"/>
</property>
</bean>


Have fun!