Posts

Showing posts with the label spring

Configuration Ownership

Image
  Building software at scale is tricky, and when you have lots of software, you have more problems to solve. Several times engineers look for ways to make their lives easier: make it simple, transparent, and easy to use. That sounds like a good idea, right? What can go wrong with that? Typing is never the bottleneck and will never be. We are all obsessed with reuse; several times, the reuse is marginal and brings way more problems than benefits. Working with an Object-Oriented Language such as Java makes a lot of sense to leverage Dependency. Injection and Ioc(Inversion of Control). Because it's easier to test the Application and also easier to change the Code. In the past, Spring Framework was all about XML; today, all configuration is pretty much done via Code. It's possible to use property files to configure some aspects of backend services written in Java with Spring, yes, but in reality, most of the Code is in the Code in the form of Java Spring Beans.  Spring Framework ...

Spring Boot @ Configuration

Image
@Configuration allows you to distribute your Spring Beans across several classes and even jars.  However, with great power comes great responsibility. IMHO you should avoid as much as possible ship configurations with @Configuration inside jars. Because it creates binary coupling on Pojos instances and that has a huge blast radius. In IMHO is completely fine to have Config beans inside in your own service however we are considering a shared libs landscape thats a completely different question and IMHO the wrong move. Let's take a look how @Configuration behavior in sense of ordering and with multiple jars being loaded to the same application.

Spring Boot Groovy Console

Image
Observability is a must-have nowadays in modern cloud services. There are multiple levels and options to provide observability into a service. Logging is the basic one but is well used can perform miracles, metrics, dashboards, and alerts and at the top of the chain however, the true nirvana is to have a self-managed / self-healing system and for troubleshooting a query interface. If you let it sink for a moment and think about it you will realize we often had such power in the past with relational databases with a SQL client for instance. However using a Spring Boot stack using polyglot persistence, with JPA, Reactive Programing, Multiple property sources, and Beans it's easy to get into the application and shared libs internals. So what's best? To have access to all properties at runtime and spring beans and be able to execute CODE in a very fluent way. That's where Groovy comes into the play. Inspired by Gabor Bata work , today I will show how we can get that and more w...

Java Agents

Image
 Java Agents are an interesting capability of the JVM. Agents can either be Static(Load when the java app starts with a special flag) or they can be Dynamic(using the dynamic API from java we can dynamically bind to a specific JVM PID. Agents can be used to run any code before the app starts or even to change the bytecode. The cool thing about agents is the fact that is a runtime thing and we do not need to change the source code of the target app. Agents are similar to Aspects but IMHO much better. Mockito uses mocks in order to test difficult scenarios, pretty much all observability solutions for logs and metrics also have agents. Today I want to share 2 pocs, one using a vanilla java app and doing bytecode manipulation, The second using Spring Boot 2.x and running code forever in a background thread as the app also runs. So Let's get started!

Restarting Spring Boot Applications

Image
Spring Boot is the standard framework for developing java services nowadays. It's more than normal to have multiple deploys into productions during the day if you are not trapped by a release calendar or release train which should be a temporary thing and end up being a permanent thing. Ideally, you will have 3 at least 3 instances of your service, one for each availability zone in AWS. In order to introduce changes, DevOps often apply a pattern called Rolled Updates where often you patch one service and restart the application and then you do that one server at a time. In order to do that you server should be able to handle a clean shutdown and manage restarts smoothly which requires some config or code in your service side and also some consideration in sense of release resources, deny connections and prepare the land for a proper restart to happen. You might be in the middle of an important transaction so maybe you want to finish that first. For services is common to use the Sag...

@Value and Spring Properties

Image
@Value annotation allows you to inject either values or results of expression into fields or even methods and constructors. Spring has several mechanisms to deal with configuration and dependency inject. IMHO for Services is more them fine to use all these features, however for libraries we need to be extremely careful and I would say you don't want to use any of these capabilities. We also need to be careful about versioning properties inside jars, especially for libraries. It's very easy to get unpredictable behavior. So great powers require great responsibility and thinking beyond anything I made a video showing some of this feature and also some simple POC - so let's get started!

Spring-Boot Native Image

Image
Spring Boot is the most popular java stack nowadays. New languages like Go and Rust are capable of creating a single binary, self-contained with all deps to run the application. This is great for deployment simplicity but also easier to maintain. As time pass we want to have fast bootup times and do more with less. The native solutions are fast since they are statically compiled for a target platform or OS(in the case of UniKernels). Java was designed to be better as time pass(Runtime) and optimizations kick in. However thats not ideal for Serverless applications. GraalVM changes that since allowing us to compile JVM applications(Java, Scala, Kotlin) to native applications. Today I want to share a simple Video + POC using a new project called Spring Boot Native which allows us to create native images to spring boot apps.  Native images have some challenges like Type Erause for C++ and Reflections in Java. So Let's get started!

NetflixOSS Domain Graph Service: GraphQL and Spring Boot

Image
NetflixOSS Released a pretty interesting new solution. A framework for GrpahQL fully integrated with Spring Boot. DGS is super easy to use. You basically have zero effort to use it with Spring boot applications. DSG works with Maven or Gradle, Java, or Kotlin. Some time ago I made some posts about GraphQL and BFF you might want to check it out here and here . You compare with this other approach(also with a video) available here . Without further due, let's get started.  The Video The Code https://github.com/diegopacheco/java-pocs/tree/master/pocs/dsg-fun Cheers, Diego Pacheco

Tests with Spring Boot MockMVC

Image
Spring and Spring Boot provide several ways to test our applications/services. Recently I made a post and video about Testing approaches that might be interesting for you. Previously I also made a post and video about TestRestTemplate  and mocks . For this post, I want to focus a bit on the MockMVC capability. MockMVC has a FakeDispatcher servlet(It will feel pretty real) simulating the MVC stack, however, there are no real network connections being made in practice. So MockMVC provides a lightweight way to test controllers as fast as possible. For this post, we will see a simple POC I wrote with a video going to set up a Spring Boot application and also test some scenarios with the MockMVC feature. So Let's Get Started! 

Spring Boot 2.x TestRestTemplate

Image
Spring has lots of interesting features to make testing easier. There are many ways we can test our application. Often tests are about confidence but not only that tests are also about having a healthy and clean mindset for maintaining systems. For one reason or another there are migrations that need to happen, either for InfoSec remands or Business wants to have a better set of a new feature for user experience or simply the team wants to make the service right and faster. No matter the reason if you have a healthy set of tests your life will be much easier. The building is easier, maintaining system health requires discipline and tests are a  very important part of it. Today I want to show how easy is for us to write proper and yet lightweight integration tests using Spring Boot 2.x and TestRestTemplate. There is a simple application I wrote and also a video which I will cover the code with more depth. So Let's get started.

Spring Boot 2.x and Mocks

Image
Spring Boot has interesting extensions for mocks using Mockito. Sometimes mocks can be very harried. Unit Tests make sense for services however the cost of mocks sometimes is too high and it could be a very time-consuming and complicated task. Spring-Boot has interesting support together with mockito to make mocks easier and more declarative. Mock is not a free lunch dont get me wrong. However, when you are coding a service Dependency Injection makes sense. Since Dependency Injection makes sense for services why such a thing would not make sense for mocks? Well, it's the same principle. If your implementation relies on dependency injection, your tests should also do the same. I have a bit of different opinion about shared libraries where I dont think they should be coupled with Spring and therefore might not have DI at All. Libraries and Services are completely different animals. Going back to services, today I want to share a video and some sample code I made to show how mocking c...

Hibernate Reactive with Spring Boot 2

Image
Reactive programming is not a new thing. Thanks to reactivex and rx-java it's a reality for almost 10 years. There are other implementations like Project Reactor  and even Vert.x . However, for Databases, we are still not there. Some databases have better support than others like Cassandra and Redis have decent support in drivers but JDBC and JPA are not quite there yet. Hibernate just went reactive. There is a hibernate-reactive project now(still beta 1.0) but looking promising. So today I want to share some simple POC I made to make Hibernate Reactive work with Spring Boot 2.x using webflux: using Netty of course. So I made a video going throught the code and explaining how it works. I personally worked with all sorts of persistence on the last +17 years on technology but not an ORM fan nowadays. However I always appreciate performance and better APIs, so I think this is promising even if is for legacy application modernization.

Spring Boot 2 running with Netty

Image
Spring Boot 2 - It's the default Java way to implement REST endpoints and microservices nowadays. I really miss old days of spring where we used XML and there was no coupling and spring was really lightweight. IMHO Spring is great if you use it under a service, If you use a shared library of the big framework, you can easily get Binary Coupling which will be bad for you in the long run.  Today I want to show how easy is to use Netty. Using netty directly is not that hard and really anyone can use without spring. Netty comes as default dependency if you use webflux instead of the web. So Let's get started. Video Code https://github.com/diegopacheco/java-pocs/tree/master/pocs/spring-boot-2-netty-fun Cheers, Diego Pacheco

Feature Enrichment with Spring Data Redis and Lettuce

Image
Lettuce by far is the best Redis client out there for Java. In the java world, Annotations and Mappings are pretty popular. I build services using these concepts before however they were always under the service boundaries, never as shared libraries in order to avoid coupling. So today I record a video showing how we can use this feature and also extend the functionality to add custom enriched behavior.  We will be using Spring Boot 2, Spring Data Redis, and Lettuce as redis Client. We also will need to have redis running either as standalone / cluster or running on docker. We will create custom annotations in order to describe the behavior we want. I need to say that some people love and other people hate annotations, I have mixed feelings. Often for those that don't like it - check this out . Besides that, let's take a look. So Let's get started.

Pure OO, Inversion of Control(IoC) + Dependency Injection(DI) and The Cake Pattern(FP): Whats really matters?

Image
Software development continues to improve, once you add new languages, design concepts, paradigms(like functional programing) we start having new ways of doing things, so whats really matters? should i change somethings and embrace everything or should i change nothing? In this post i want cover something if you was java developer was the central idea around java development for years. Spring Framework dominate the fields for more than a decade. The real question is not if  you should be using XML or annotations(like Guice ). Either if you should go XML or java Annotations. Thats kind of old discussion, so basically what are the options now a days?

Fun with REST, Spring 3 and Jasper

Image
Hey folks, in this post i will show how to have fun coding Web services with REST, Spring 3 and Jasper Reports. First of all i will give you some background about REST. We gonna code our Web Service REST using Apache CXF . You can work the old way, with CXF using the standards like ws-* but here we will use REST only. Why REST? REST(Representational State Transfer) is not a standard. It is an Architectural Style defined in 2000 by Roy Fielding . The Style basically consist in leverage http method like PUT, DELETE and not be stuck only to POST and GET. With REST your are not limited to XML, you have freedom to work with different media types(data format) like Json , Protobuf , binary, raw text or whatever media-type you want even xml. REST is simply. I don't know if it will remain for long time but pray all day for that happen :-). There are a couple of enemies trying to transform REST in something more look like ws-*, such wadl (very nasty). I know you guys want some way to ...

Governança SOA com Mule Galaxy parte 2: Maven e Spring

Image
No post anterior contei sobre a importantancia da governança em uma adoção de SOA. Também comentei um pouco sobre o Mule Galaxy, uma solução open source para governança SOA em tempo de runtme. Neste post vou mostrar como registrar ativos no Mule Galaxy usando o plugin do maven que o Galaxy prove, além disso vou mostrar como recuperar as configurações do Spring Framework. O que vamos fazer? Criar um projeto no maven que consegue fazer deploy de ativos no Mule Galaxy usando o plugin de publicação do Galaxy para o Maven. Vamos criar um bean no spring e um arquivo de configuração deste bean para o Spring e também vamos registrar este bean como ativo no Galaxy bem como um WSDL de um webservice. Instalando e Rodando o Mule Galaxy Basta baixar o war do Galaxy e colocar no seu servidor de web, eu vou utilizar no Jetty, mas poderia se outro se você quizer por exemplo, você deve rodar a solução com JDK 6 update 10 ou superior para não ter problemas com XML. Estou usando a versão 1...

Integração Simplificada com Apache Camel

Image
Integração de sistema sempre foi e sempre sera uma necessidade para qualquer departamento de TI.Esta integração é feita na maioria das vezes de forma manual e pontual, este tipo de abordagem trás diversos problemas como por exemplo a complexidade de construir a integração sem utilizar um framework que lhe de beneficios como padrões, design certo a seguir, reutilização de código, reuso. É normal se você estiver pensando em um ESB , porem um ESB requer muito conhecimneto, pensamento em design e você vai ter que lidar com uma certa complexidade. Neste post vim falar do Apache Camel que é um framework de integração de sistemas como se fosse um *ESB-Leve* fortemente baseado em Spring . O Camel é um solução open source da Apache muito simples e extremamente flexivel, parte da sua flexibilidade é dada através da sua excelente integração com o Spring Framework. Este framework não apénas facilita a sua vida quando você trabalha com JMS ou WebServices por exemplo, facilita também quan...

Extensão do Curso de Spring Framework

Pessoal, é com orgulho que venho publicar o primeiro anexo de atualização e novos recursos ao curso de Spring Framework . O curso que disponibilizei era focado em Spring 2.X sendo que todos os recursos eram válidos para o Spring 2.5, agora neste anexo vou mostrar as novas facilidades de anotações do Spring 2.5 e bem como novos recursos como JMX, JSF e testes com o TestNG, vários destes recursos já existiam no spring 2.0 mas não estavam presentes no curso, agora você pode utilizar estes recursos nesta nova apostila que é incremental a apostila do curso. Confira o conteúdo detalhado deste anexo: Anotações @Required @Autowired @Qualifier @PostConstruct @PreDestroy @Service @Repository @Component @Resource Testes com anotações e TestNG AbstractTestNGSpringContextTests @Test Integração com JSF e Jboss RichFaces Configuração de toda aplicação e utilização Expondo Beans com JMX MBean Exporter Para este anexo que chamei de Anotações e Web você tem a disposição os sli...

Curso Gratuito de Spring Framework

Em 2007 eu criei este curso de Spring framework. Hoje é com grande satisfação que venho disponibilizar este material. Você pode baixar o material e utiliza-lo para estudo e até mesmo para ministrar cursos. Neste curso são abordados as principais funcionalidades do núcleo do Spring Framework... Confira a apostila completo do curso a baixo: Spring Framework 2.0 - Diego Pacheco Este curso conta com 5 slides para condução do curso, você pode obter todos estes slides na minha conta do SlideShare , dentre outras apresentações que fiz. Confira os Slides a baixo: Spring Capitulo 01 View more presentations from Diego Pacheco . Spring Capitulo 02 View more presentations from Diego Pacheco . Spring Capitulo 03 View more presentations from Diego Pacheco . Spring Capitulo 04 View more presentations from Diego Pacheco . Spring Capitulo 05 View more presentations from ...