Hello dear friends ūüôā

Welcome to the second Post about Spring Boot 2 Guru Serie , in the previous article Part1 , we presented how to create and test a  basic spring boot project and explained basic class files and maven dependencies .

In this post we will dive into more amazing features of Spring Boot .

Objectives

    After completing this part  , you should be able to :

    • Explain how Auto-Configuration drives Spring Boot
    • Use various Techniques to customize Spring Boot Application
    • Implement Configuration Properties
    • Configure Logging
    • Use YAML alternative for Spring Boot Configuration

    Understand Auto-Configuration

    As a developer , you may ask yourself  : Why do we need Spring Boot Auto Configuration?

    Great !  Simply because Spring based applications have a lot of configuration !

    For example when we use JPA with Spring Framework , we would need to configure beans  such as LocalContainerEntityManagerFactoryBean , DataSource and  PlatformTransactionManager : 

    @Configuration
    @EnableTransactionManagement
    public class PersistenceJPAConfig{
    
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
            LocalContainerEntityManagerFactoryBean em
                    = new LocalContainerEntityManagerFactoryBean();
            em.setDataSource(dataSource());
            em.setPackagesToScan(new String[] { "com.java.ways.model" });
    
    
            JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            em.setJpaVendorAdapter(vendorAdapter);
            em.setJpaProperties(additionalProperties());
    
    
            return em;
        }
    
    
        @Bean
        public DataSource dataSource(){
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/spring_jpa");
            dataSource.setUsername( "springbootguru" );
            dataSource.setPassword( "javaways" );
            return dataSource;
        }
    
    
        @Bean
        public PlatformTransactionManager transactionManager(
                EntityManagerFactory emf){
            JpaTransactionManager transactionManager = new JpaTransactionManager();
            transactionManager.setEntityManagerFactory(emf);
    
    
            return transactionManager;
        }
    

    An other example when we configure JMS within Spring :

    @Configuration
    
    @EnableJms
    public class AppBlogConfig {
    
    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
    DefaultJmsListenerContainerFactory factory
    = new DefaultJmsListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory());
    //core poll size=4 threads and max poll size 8 threads
    factory.setConcurrency("4-8");
    return factory;
    }
    }
    

    So ,  Auto-configuration is one of the important features in Spring Boot because it configures your Spring Boot application according to your classpath, annotations, and properties.

    To understand Auto Configuration further, let’s run our simple Spring Boot Application from the¬†last Part 1

    We need just to take some modification:

     we will use In memory database HSQLDB to store and retrieve data via the Spring support class   JdbcTemplate  ( we will cover this class later in next posts ).

    So  open your spring-boot-basic project and apply these modifications :

    • New POJO¬† Blog.java¬† ¬†: we add a new Java POJO to map our databasa table
    package com.java.ways.boot.basic;
    public class Blog {
    
    private long id;
    private String name;
    private String mail;
    
    @Override
    public String toString() {
    return String.format(
    ‚ÄúBlog[id=%d, name=‚Äô%s‚Äô, mail=‚Äô%s‚Äô]‚ÄĚ,
    id, name, mail);
    }
    
    //Getter Setter and Cosntructor 
    
    }
    • Maven pom.xml


    <dependencies>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    </dependency>

    </dependencies>

    • Resources directory
    drop table T_BLOG if exists;
    create table T_BLOG (ID integer identity primary key,  NAME varchar(50) not null, MAIL varchar(50) not null );
    insert into T_BLOG (ID, NAME, MAIL) values ('11', 'JAVA-WAYS.COM', 'med.ingenieur@gmail.com');
    insert into T_BLOG (ID, NAME, MAIL) values ('22', 'JAVA', 'java@gmail.com');
    insert into T_BLOG (ID, NAME, MAIL) values ('33', 'TUNISIA.COM', 'tunsianWay@gmail.com');
    
    • SpringBootBasicApplication.java
    Finally we update our entry class to get data from in memory database  :

    @SpringBootApplication
    public class SpringBootBasicApplication {
    private static final Logger log = LoggerFactory.getLogger(SpringBootBasicApplication.class);
    
    public static final String QUERY = "SELECT * from T_BLOG";
    
    public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(SpringBootBasicApplication.class, args);
    
    JdbcTemplate jdbcTemplate = ctx.getBean(JdbcTemplate.class);
    jdbcTemplate.query(
    QUERY,
    (rs, rowNum) -> new Blog(rs.getLong("id"), rs.getString("name"), rs.getString("mail"))
    ).forEach(blog -> log.info(blog.toString()));
    }
    

    Finally , check your console after running the Spring Boot application  :

    As we may notice here , Spring boot initialized for us an embedded database , populate it with data and display result via default created  JdbcTemplate class .

    If we check the list of beans created per default by Spring Boot , we notice that just we added the starter jdbc and HSQLDB in the pom file , Spring Boot auto-configured for us new beans :

    What we should keep from this exercise ? 

     

    Until Now we satisfied our first objective of this post  :

    • Explain how Auto-Configuration drives Spring Boot¬†¬†
    • Use various Techniques to customize Spring Boot Application
    • Implement Configuration Properties
    • Configure Logging
    • Use YAML alternative for Spring Boot Configuration¬†

    Please  find all the code for this section here :

    ¬†Let’s move¬† to the our next Goal ! ūüôā

    9+

    Mohamed Ben Hassine

    Hello , I am a Software Technical Leader  / Lover / Speaker / Blogger / Trainer with over 9 years of experience in designing and developing financial and telecommunication large scale enterprise applications using Web / Java/JEE technologies. Open to multi-culture customers and workplaces, I help companies and individuals build scalable Web Applications using last proved web technologies and enterprise software architectures.

    8 Comments

    Hamza ouni · 10 January 2019 at 11 h 46 min

    Thank you

      Mohamed · 10 January 2019 at 12 h 02 min

      Not at all Hamza , let me know if I can help you further ūüôā

        Hamza ouni · 10 January 2019 at 12 h 30 min

        How HSQLDB was added to the classpath and we don’t add it

          Mohamed · 10 January 2019 at 12 h 32 min

          Hello Hamza ,

          We added this HSQLDB in the pom.xml : hsqldb , ( so Maven will add it to the application classpath )

          Regards

            Hamza ouni · 10 January 2019 at 12 h 33 min

            Clear , thank you

            Mohamed · 10 January 2019 at 12 h 34 min

            Welcome Hamza , Dont hesitate to contact me for detailed explanation ūüôā

    Hamza ouni · 10 January 2019 at 16 h 56 min

    i am so thankful

    Leave a Reply

    Your email address will not be published. Required fields are marked *