Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Monday, September 30, 2019

beauty of Spring Data



thanks to Greg Turnquist

https://www.slideshare.net/SpringCentral/introduction-to-spring-data

https://spring.io/guides/ type "data"

my code is available here https://github.com/vernetto/springdata

Saturday, July 13, 2019

Book: Spring Microservices in Action


This is a brilliantly written book.

https://github.com/carnellj/spmia-chapter1

Microservice Architecture

@SpringBootApplication
@RestController
@RequestMapping
@PathVariable

Flexible, Resilient, Scalable

IaaS, PaaS, SaaS, FaaS, CaaS

Client-side load balancing, Circuit breaker, Fallback, Bulkhead

Log correlation. Log aggregation. Microservice tracing

Spring Cloud:
Netflix Eureka (discovery), Zuul (routing), Ribbon (LN), Hystrix (Circuit Breaker), Sleuth/Uipkin (logging, tracing, aggregation), Oauth2/JWT

https://cloud.spring.io/spring-cloud-security/ Spring Security

https://jwt.io JavaScript Web Token

https://travis-ci.org


Hystrix proxies all RestTemplate. calls to add timeout. Ribbon also injects RestTemplate with all available service instances for LB and FO


to expose a bean there are 2 ways:
either one of @Component, @Service, @Repository
or @Configuration + @Bean


Apache Thrift, Apache Avro

12 factor apps: codebase in git, dependencies in maven, config in separate files, backing services (DB etc) cloud-ready,
immutable builds, stateless processes, port binding, horizontal scaling, disposable services, dev=prod, streamable logs (splunk, fluentd), scripted admin tasks.


Actuator health check.








Sunday, June 16, 2019

Spring bean lifecycles and BeanPostProcessor


import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class MyComponent implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet from InitializingBean");
}

@PostConstruct
public void onPostConstruct() {
System.out.println("onPostConstruct");
}

@PreDestroy
public void onPreDestroy() {
System.out.println("onPreDestroy");
}


@Override
public void destroy() throws Exception {
System.out.println("destroy from DisposableBean ");
}


}

the sequence is:

onPostConstruct
afterPropertiesSet from InitializingBean
onPreDestroy
destroy from DisposableBean



and you can intercept instantiatio of every bean with a BPP :


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomBeanPostProcessor implements BeanPostProcessor {

    public CustomBeanPostProcessor() {
        System.out.println("0. Spring calls constructor");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }
}



Monday, April 1, 2019

Best Spring books

reblogging for my own reference, I am planning to read all those 5 books...

https://javarevisited.blogspot.com/2018/04/5-spring-framework-books-experienced-Java-developers-2018.html

- Spring in Action 5
- Cloud Native Java
- Learning Spring Boot 2.0
- Spring 5 Recipes
- Spring Microservices in Action



I am already going through https://www.udemy.com/spring-framework-5-beginner-to-guru/ but I find it incredibly non-concise - lot of repeated stuff, very lengthy and boring coding sessions where you don't really see much new, lot of unnecessary verbosity. Not my style, I like crisp, focused, simple examples and just fundamental facts and concepts.


Friday, September 21, 2018

Parsing command line arguments in Spring etc

lots of frameworks are reported here:
https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java/


but eventually I just want to do it using Spring classes

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html

The advantage in Spring is that you can directly bind the command line arguments to attributes, there is an example here

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html



A very simple example:

package org.pierre.clidemo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.boot.CommandLineRunner;


@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

 @Override
 public void run(String... args) throws Exception {
  PropertySource ps = new SimpleCommandLinePropertySource(args);
  // --file=pippo.txt --language=EN_TO_DE --firstOriginal=true
  System.out.println("file=" + ps.getProperty("file"));
  System.out.println("language=" + ps.getProperty("language"));
  System.out.println("firstOriginal=" + ps.getProperty("firstOriginal"));
 }
}



and of course the JOptCommandLinePropertySource version is more robust...


Interesting also the https://projects.spring.io/spring-shell/ project, but only to write CLI applications







Sunday, July 22, 2018

Spring Boot Security 5 and Oauth2




https://github.com/jgrandja/springone2017-demo


Ultimate guide and examples:

https://docs.spring.io/spring-security/site/docs/5.1.0.M1/reference/htmlsingle/

https://github.com/spring-projects/spring-security/blob/5.1.0.M1/samples/boot/oauth2login/README.adoc



Here a very rich presentation on Oauth2:

https://ordina-jworks.github.io/microservices/2017/09/26/Secure-your-architecture-part1.html

https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2


Spring boot Oauth2 https://spring.io/guides/tutorials/spring-boot-oauth2/



A simple application: https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_simple
Code is here https://github.com/spring-guides/tut-spring-boot-oauth2.git or also https://github.com/vernetto/springboottests/tree/master/ui

Here the OAuth2 specs https://tools.ietf.org/html/rfc6749#section-4

Nice simplified and compact presentation https://aaronparecki.com/oauth-2-simplified/


Baeldung example for Oauth2 here https://github.com/eugenp/tutorials/tree/master/spring-5 with explanation here http://www.baeldung.com/spring-security-5-oauth2-login








Wednesday, May 23, 2018

Zuul and Spring Cloud

http://cloud.spring.io/spring-cloud-netflix/

Training is here https://spring.io/guides/gs/routing-and-filtering/

https://github.com/spring-cloud/spring-cloud-netflix

Service Discovery (Eureka)

Circuit Breaker (Hystrix)

Intelligent Routing (Zuul)

Client Side Load Balancing (Ribbon)




Monday, May 21, 2018

Spring Cloud, getting started

http://www.baeldung.com/spring-cloud-bootstrapping


generate your starter zip from http://start.spring.io/ :

http://start.spring.io/starter.zip?type=maven-project&language=java&bootVersion=2.0.1.RELEASE&baseDir=config&groupId=org.pierre&artifactId=config&name=config&description=Demo+project+for+Spring+Boot&packageName=org.pierre.config&packaging=jar&javaVersion=1.8&autocomplete=&generate-project=&style=cloud-config-server


unzip it
add import org.springframework.cloud.config.server.EnableConfigServer; and @EnableConfigServer to ConfigApplication

cd
mkdir application-config
cd application-config
git init


mvn spring-boot:run




http://callistaenterprise.se/blogg/teknik/2015/04/10/building-microservices-with-spring-cloud-and-netflix-oss-part-1/

git clone https://github.com/callistaenterprise/blog-microservices.git



Spring Integration Sucks

Here the whole tutorials site https://github.com/eugenp/tutorials to git clone

If you use Eclipse, better to "git clone" separately and then Import, Existing Maven Project, and give the tutorials folder. Importing from Git seems not to work (Eclipse SUCKS, it's the most pathetic IDE in centuries).

This is the one interesting us https://github.com/eugenp/tutorials/tree/master/spring-integration


All is explained here http://www.baeldung.com/spring-integration (BasicIntegrationConfig in the github project is FileCopyConfig)

My first impression is of an extreme complication and non elegant API design. You have to wade through a ton of annotations, abstractions, base classes, non-fluent APIs, just to copy a file from A to B. Camel seems to me much more essential - maybe because Camel was designed with Integration as primary focus, while Spring Integration just add some Integration functionality to the hyper-complex bloated Spring monster.


Look at all the import you need to just copy a file every 1 second:

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.FileReadingMessageSource;
import org.springframework.integration.file.FileWritingMessageHandler;
import org.springframework.integration.file.filters.SimplePatternFileListFilter;
import org.springframework.integration.file.support.FileExistsMode;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;


simply ridiculous.



Friday, April 6, 2018

Spring core tutorial

Although a bit outdated, it goes over the main points https://www.tutorialspoint.com/spring/

I have put the code of each step in https://github.com/vernetto/springdemo , instructions in the readme.md, a separate tag for each step. The class to run is MainApp.



Spring testing

spring-test

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html

spring-boot-test

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

@ContextConfiguration(locations = "/test-db-context.xml")

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.pierre.sourcing.dao, com.pierre.xcoll.dao" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@pippo:1521:PLUTO" />
        <property name="username" value="pippouser" />
        <property name="password" value="pippopassword" />
    </bean>

    <bean id="transManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource" />
    </bean>

    <context:component-scan base-package="com.pierre.sourcing.dao" />
</beans>



Important annotations

org.springframework.test.annotation.Rollback; indicates whether the transaction for a transactional test method should be rolled back after the test method has completed.

org.springframework.transaction.annotation.Transactional

org.springframework.test.context.ContextConfiguration @ContextConfiguration("/test-config.xml") declares the application context resource locations or the annotated classes that will be used to load the context.

org.springframework.test.context.jdbc.Sql at class level, like in @Sql(scripts = "/preparation-sqls/cleanup-test-data.sql") , to run SQL BEFORE the test execution

org.springframework.test.context.junit4.SpringRunner (@RunWith(SpringRunner.class) )

org.springframework.beans.factory.annotation.Autowired



Friday, September 1, 2017

Spring Framework Essentials course by Ken Kousen in Safari Books Online

Here is the code https://github.com/kousen/Spring-Framework-Essentials

Ken is a very talented teacher, who focuses on concepts rather than sheer data. Highly recommended.

The course is available only if you register in Safari Books Online https://www.safaribooksonline.com/, but there is a short term FREE evaluation account (no credit car required).



Friday, August 11, 2017

Spring boot Rest controller with Embedded Tomcat



really simple, and the code is available here

https://github.com/vernetto/restapi

I just realize that I had already done this exercise here http://www.javamonamour.org/2017/03/spring-boot-starter-web-app.html , even better explained!

Sunday, February 12, 2017

Saturday, February 11, 2017

Great Spring basic introduction part 2

part 10

part 11


part 12

part 13

part 14

part 15

part 16

part 17

part 18

part 19

part 20

part 21

part 22

part 23

part 24


Friday, February 10, 2017

Great Spring basic introduction (part 1)

part 1

part 2

part 3

part 4

code for part 4 is here https://github.com/vernetto/JavaMonAmour/tree/master/SpringDemo
part 5

part 6

part 7

part 8
part 9






Thursday, March 12, 2009

Logging Return Value and Method Arguments with Spring AOP

as in the previous example, but use this:


<aop:after-returning method="logExitAfterReturn" ref="loggingPointcut" returning="retVal"></aop:after-returning>


and the method becomes:

public void logExitAfterReturn(final JoinPoint joinPoint, Object retVal)

{
log( "Exiting method (after return) " + joinPoint.getSignature().getName() + ", retValue = " + retVal + ".");
}


while the logEntry becomes:

public void logEntry(final JoinPoint joinPoint)

{

StringBuilder arguments = new StringBuilder();

arguments.append(" args= ");

for (Object arg : joinPoint.getArgs()) {

arguments.append(arg).append(", ");

}

log("Entering method " + joinPoint.getSignature().getName() + arguments.toString() + "...");

}