Spring Boot - Java

  • Microservices Architecture
  • Spring Boot
    • Provides RAD (Rapid App Development), Maven based
    • Project Structure
    • @SpringBootApplication
      • This annotation serves the purpose of
        • @Configuration => Used to declare a class as component class
          • Normally placed in class having main
        • @EnableAutoConfiguration
          • Attempts to automatically configure app based on jar dependencies present in the class path, maybe by reading the application.properties
        • @ComponentScan
          • Used to scan the stereotype annotations in the current package and child package, where the primary configuration class is present
    • Deploy app using
      • Run primary configuration having main class => Run java project
      • Run using Spring Boot Maven Run
        • Goal = clean install spring-boot:run
      • Run jar file created by the end of maven build (clean install) using
        • java -jar
    • For Spring Rest & Spring JPA based boot application
      • Config spring-boot-starter-data-jpa artifact in pom.xml
  • Configure Jetty Container as Default
    • Version Tomcat 8, Servelet 3.1, Java 7+
    • Configure jetty server in pom.xml as dependency
    • URLs will not be exposed in the console log
  • Content Negotiation
    • Decide upon the MIME type/Content type of that content that is being send back to client from server
    • Strategies
      • URL extension based
      • URL parameter based
      • Accptence header based
    • Steps
      • Create custom COntentNegotiationManager by following a strategy and override existing
      • Link to primary configuration
      • Let the handlers of RestController produces multiple MIME type/Content type
  • Spring Boot REST Validations
    • Hibernate bean validation APIprovides set of constraints to validate data before any persistance operation
    • Configure ValidationMessages.properties in order to make validation messages independent of the messages
  • Spring Boot Profiles
    • Used for selective loading of the application components baed on the type of environement
    • @Component needs to be marked with @Profile annotation for selective loading
    • Use spring boot auto configured loaggig
      • static private Logger logger = LoggerFactory.getLogger("")
      • This class is loaded only when profile is active
    • Can be activated using
      • application.properties file, by adding spring.profiles.active=p1, p2,...
        • spring.profiles.active=prod_profile
        • spring.profiles.active=test_profile
      • Command line: clean install spring-boot:run spring.profiles.active=p1,p2...
      • @ActiveProfile annotation [this way is possible only for test cases]
        • clean install spring-boot:run -Dspring.profiles.active=prod_profile
        • clean install spring-boot:run -Dspring.profiles.active=test_profile
      • SpringApplication.setAdditional Profiles(...) in primary configuration by making use of ConfigurableEnvironment
      • application-{profile}.properties => Profile specific files
  • Customize Embedded Servlet Container
    • Project should have following 2 deplouments, should also exist in parallel
      • Deployment is testing environment where it should not hit database/Map based CRUD and DB layer should not be loaded
      • Deployment is production environment where it should hit database/Map based CRUD
    • All the customizer should implement EmbeddedServeletContainerCustomizer
      • All customizer should be spring componenet
      • Override the method customize
  • Spring Boot Runners
    • Used to perform any task just after all the beans and ApplicationContext are created in SpringBoot application
    • Types of interfaces
      • Application Runner [public void run(ApplicationArguments arg0) throws Exception]
      • CommandLineRunner [public void run(String... args)]
    • In order to create runners following steps need to be followed
      • Create a Class implementing any of the required interface
      • Override the run() method
      • Register the class as a Spring Component by using any of the stereotype annotations
    • @Ordered(position) annotion is used to change the order of execution if multiple runners
  • Layers to be tested & Technology to be used
    • Service Layer => Junit, Spring Testing Framework
      • Config pom.xml
    • Controller Layer Integration Test => Junit, SpringMockMVCTest framework
    • Controller Layer Unit Test => Junit, Mockito, Spring MockMVCTest framework
  • YAML (Ain't Markup Language) Configuration
    • Human readable data serializition luanguage used to configure files
    • Can replace application.properties by application.yml
    • @PropertySource used to load the custom file, but can't open .yml files
      • YEdit pludin needs to be installed
      • @ConfigurationProperties("") works with .yml and .properties both
  • Deploy Spring Boot App on External Server => Packaging the app as war
    • Provide implementation for SpringBootServeletIntializer, which contins configure() method
    • Change packaging to war in pom.xml
    • Scope of embedded container is set to "provided", as it should not become part of packaged artifact
    • Code
      • <role rolename="manager-gui"/>
      • <user username="tomcat" password="secret" roles="manager-gui"/>
  • Spring Boot REST Client
    • RestTemplate Methods
      • getForObject, postForObject, put, delete
    • Steps
      • Go to OD > tomcat > bin > Run Catalina.bat
      • Paste this code in notepad
        • <role rolename="manager-gui"/> <user username="tomcat" password="secret" roles="manager-gui"/>
      • Go to conf > Open CMD > Run Catalina run > Open URL
        • Username = tomcat
        • Password = secret
      • Manage Project > Upload WAR file
  • Bean Lifecycle methods
    • Configure the init method and destroy method in bean definition
      • <bean id="helloBean" class="com.accenture.lkm.bean.HelloBean" init-method="init" destroy-method="destroy"/>
    • Bean class is implementing InitializingBean, DisposableBean and overriding
      • afterPropertiesSet, destroy
    • Lifecycle annotation
      • Annotate your bean's methods with @PostConstruct and @PreDestroy
      • Config file
        • <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
    • GlobalBean - init and destroy
      • WelcomeBean - init1 and destroy1(configured same as approach 1)
      • HelloBean - init2 and destroy2(configured same as approach 1)
      • GlobalBean bean definition is done, default-init-method="init" default-destroy-method="destroy"
    • A class is created by implementing BeanPostProcessor and overriding
      • postProcessBeforeInitialization
      • postProcessAfterInitialization
      • This bean should be configured in xml file
    • A class is created by implementing BeanFactoryPostProcessor and overriding postProcessBeanFactory
      • This bean should be configured in xml file
    • Externalizing the properties and reading them from xml file itself
    • Working with environment specific properties file
Share: