Posts

Showing posts with the label spring

Smart package structure to improve testability

There are many ways of dividing whole application into packages. Discussions about pros and cons of packaging by feature or by layer can we found on many programming blogs and forums. I want to discuss this topic starting from testability and see if it will drive to any meaningful result. At the beginning let's try to describe what we usually want to test in our applications across different layers. Let's assume standard three tier architecture. At the bottom we have data layer. Depending on our attitude to Domain-Driven-Design we'll try to maximize (for rich, business-oriented entities) or minimize (for anemic entities built only from getters and setters) test coverage. In the second approach it's even hard to say about any tests, unless you don't trust Java and want to verify if get can retrieve value assigned before by set invocation. For rich entities we definitely want to verify business logic correctness. But to be honest it almost always can be done by si...

Dependency injection pitfalls in Spring

There are three injection variants in Spring framework: Setter-based injection Constructor-based injection Field-based injection Each of those mechanisms has advantages and disadvantages and there is not only one right approach. For example field injection: @Autowired private FooBean fooBean; It's generally not the best idea to use it in the production code, mostly because it makes our beans impossible to test without starting Spring context or using reflection hacks. On the other hand it requires almost no additional code and could be used in integration tests - which definitely won't be instantiated independently. And in my opinion this is the only case for field-based injections. Now let's focus on two major variants. In  Spring documentation  we can read that ...it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Also in documentation referring Spring up to 3.1 we could find a sentenc...

Including Java agent in standalone Spring Boot application

Recently at DevSKiller.com  we've decided to move majority of our stuff to simple containers. It was pretty easy due to use of Spring Boot uber-jars, but the problem was in  NewRelic  agents which should have to be included separately. That caused uncomfortable situation so we decided to solve it by including NewRelic agent into our uber-jar applications. If you also want to simplify your life please follow provided instructions :) At first we have to add proper dependency into our pom.xml descriptor: <dependency> <groupiId>com.newrelic.agent.java<<groupId> <artifactId>newrelic-agent</artifactId> <version>3.12.1</version> <scope>provided</scope> </dependency>

Managing Spring Boot application

Spring Boot  is a brand new application framework from Spring. It allows fabulously quick development and rapid prototyping (even including CLI ). One of its main features is to work from single "uber jar" file. By "uber jar" I mean that all dependencies, even an application server like Tomcat or Jetty are packed into a single file. In that we can start web application by typing java -jar application.jar The only thing we're missing is the managing script. And now I want to dive into that topic. Of course to do anything more than starting our application we need to know its PID. Spring Boot has a solution named  ApplicationPidListener . To use it we need to tell SpringApplication we want to include this listener. And there are to ways to achieve that.

Spring Java Config 101

After my last article there were some questions about how Java configuration work in details, and we can extend it to suite our needs. So I'll try to answer those question in this post :) Heart of Spring java configuration mechanism are  @Configuration classes. That's the place where we can define all properties of our Spring context. Assuming that we lean our application on annotations (which should be true if we want to use java config) we create beans using  @Component annotation (with derivatives like  @Repository , @Service and @Controller ). Varying annotations apply for different layers: @Component generic for any compoenents @Repository persistence layer @Service service layer @Controller presentation layer

Understanding Spring Web Initialization

Few years ago majority of us were used to write XML config files everywhere, to setup even simple Java EE application. Today using Java or Groovy to configure projects is becoming preferred way - you just need to take a look at Gradle or functionalities introduced in further versions of the Spring Framework to gen up on this. Now I'll deal with configuring Spring contexts for web application. Java EE provides ServletContainerInitializer interface, which allows libraries to be notified of a web application startup. Since Spring 3.1 we have SpringServletContainerInitializer class which handles WebApplicationInitializer by instantiating all found classes implementing this interface, sorting them basing on @Order annotation (non-annotated classes gets the highest possible order, so they are processed at the end) and invoking onStartup() method.

Spring integration testing with Spock

I'm currently working on a project where we use Spring Framework 4.0 and Spock for testing. Unit testing in Spock is really great, but there are some lacks in integration testing - especially in mocking Spring beans. Our requirement is to start up Spring context but with particular bean replaced with mock. The easiest part we had do implement is just regular Spring test specification: @ContextConfiguration( classes = [GatewayConfig, PaymentServiceConfig]) class PaymentServiceSpecIT extends Specification { final String CLIENT_ID = "54321" @Inject PaymentService paymentService def "Should return auth token"() { when: def token = paymentService.getAuthToken(CLIENT_ID) then: token } }

Injecting Spring beans into non-managed objects

Advantages coming from dependency injection can be addicting. It's a lot easier to configure application structure using injections than doing all resolutions manually. It's hard to resign from it when we have some non-managed classes that are instantiated outside of the container - for example being part of other frameworks like Vaadin UI components or JPA entities. The latter are especially important when we're using Domain Driven Design . During DDD training ran by Slawek Sobotka  we were talking about options to remove "bad coupling" from aggregate factories. I'm sure you'll admit, that it's better to have generic mechanism able to "energize" objects by dependencies defined by e.g. @Inject annotation than inject all necessary dependencies into particular factory and then pass them into object by constructor, builder or simple setters. Spring framework brings us two different solutions to achieve such requirement. I'll now describe ...