Codinko- Java Coding Tutorials

Category: Uncategorized (page 1 of 7)

Types of Spring Dependency injection and what to use

Injection types

There are three options for how dependencies can be injected into a bean:

  1. Through a constructor.

    @Component
    public class MyComponent {
        private final Trade t;
    
        @Autowired
        public MyComponent(Trade t){
           this.t = t;
        }
    }
  2. Through setters or other methods.

    – When you use @Autowired on the setter method.

  3. Through reflection, directly into fields.

    – when you use @Autowired directly on your field

    @Component
    public class MyComponent {
        @Autowired
        private Trade t;
    }

Injection guidelines

A general guideline, which is recommended by Spring (see the sections on Constructor-based DI or Setter-based DI) is the following:

  • For mandatory dependencies or when aiming for immutability, use constructor injection
  • For optional or changeable dependencies, use setter injection
  • Avoid field injection in most cases

Why Field injection is to be avoided?

The reasons why field injection is discouraged are as follows:

  • You cannot create immutable objects, as you can with constructor injection
  • Your classes have tight coupling with your DI container and cannot be used outside of it
  • Your classes cannot be instantiated (for example in unit tests) without reflection. You need the DI container to instantiate them, so your test is not actually a ‘unit’ test, but integration test!
  • It is really easy to have like ten dependencies. If you were using constructor injection, you would have a constructor with ten arguments, which would signal that something is wrong. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing, and that it may violate the Single Responsibility Principle.

Summary

  • Depending on your needs, you should primarily use constructor injection or some mix of constructor and setter injection.
  • Field injection has many drawbacks and should be avoided.

Reference: https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it

 

lightweight framework and Why Spring is called a lightweight framework

Why Spring is called a lightweight framework

  • Spring is considered lightweight compared to traditional Java EE applications.
  • It is lightweight because it allows minimally invasive development with POJOs.
  • We consider Spring to be lightweight when we are comparing to normal J2EE container.
  • It is lightweight in the sense of extra memory footprint for the facilities provided (e.g. Transaction Control, Life Cycle, Component dependency management)
  • Spring calls itself ‘lightweight’ because you don’t need all of Spring to use part of it. For example, you can use Spring JDBC without Spring MVC.
  • Spring provides various modules for different purposes; you can just inject dependencies according to your required module. That is, you don’t need to download or inject all dependencies or all JARs to use a particular module.
  • Whether it is “lightweight” or “heavyweight”, it is all about comparison. We consider Spring to be lightweight when we are comparing to normal J2EE container. It is lightweight in the sense of extra memory footprint for the facilities provided (e.g. Transaction Control, Life Cycle, Component dependency management)
  • However, there are sometimes other criteria to compare for the “weight” of a container, e.g. intrusiveness in design and implementation; facilities provided etc.
  • Ironically, Spring is sometimes treated as heavy weight container when compared to other POJO-based container, like Guice and Plexus.
  •  “lightweight” is mostly a buzz-word. It’s meaning is highly subjective and based on context. It can mean “low memory footprint”, it can be low execution overhead, low start-up overhead. People also use it to differentiate between some perceived level of complexity and/or learning-curve. In any case, it’s assuredly relative as there is no defined point on any scale where “light” becomes “heavy” in terms of “weight”.

What is a Lightweight Web Application

For this we need to understand a heavyweight web application.

  • The primary focus of J2EE is for developing distributed and loosely coupled middleware applications
  • Those applications typically have a web front end and a relational database backend. As web applications become popular in recent years, J2EE has gained wide acceptance among developers. In fact, J2EE is one of the few dominant web application platforms today.
  • However, as J2EE is more widely used, developers are also increasingly frustrated by its complexities.
  • The original design of J2EE addresses the distributed computing problems and application scalability problems that only the biggest enterprises encounter.
  • Apart from deviating from the original design reason, Most developers use J2EE to develop small to middle sized web applications.
  • Those “enterprise features” not only are of limited use but also add unnecessary complexity to otherwise simple web applications.
  • The problems have grown as J2EE has evolved and added more features to address a wider range of enterprise use cases.
  • In order to make enterprise Java more appealing to majority of developers who work with small web applications, the Java community has made major efforts to simplify Java web and middleware frameworks.
  • The enterprise Java specification after J2EE 1.4 is called Java EE 5.0. This change highlights the significant changes lightweight frameworks brought to the enterprise Java standards.

The J2EE 1.4 specification, released in 2004, is the last version of heavyweight J2EE.

What is a typical JEE application?

  • A typical J2EE web application has servlets that take in user input and generate the response by displaying JavaServer Pages.
  • The servlet delegates business operations and database-related work to an EJB (Enterprise JavaBeans) module containing session bean objects and entity bean objects.
  • The stateless session bean typically contains transactional methods to perform business operations.
  • Those methods are exposed to the servlet.
  • The session bean makes use of entity beans to access the relational database.
  • In the XML configuration files, we define how to use container services (e.g., transactions and security) from the session beans, as well as how the entity beans are mapped to database tables.
  • Figure 1.1, “Architecture of a J2EE 1.4 web application” shows the above-described architecture
  • Since the EJB managed components cannot be serialized out of the container, we have to use value objects to exchange data across the layers (i.e., method call parameters and return values).

Architecture of a J2EE 1.4 web application

All the J2EE components work together to serve a common purpose”

  • to make the application more scalable.

    Below is a list of key architectural characteristics that makes J2EE great.

    Component-based architecture:

    J2EE components are advanced forms of Java objects. Each component completely encapsulates its own code, configuration, and outward interface. The entire application can be composed from a set of reusable components. Those components can reside on a single computer or on a network of computers to improve application scalability. As we will see in the next several bullet items, components make the application simpler and easier to maintain.

    Loose coupling between components:

    When J2EE components make method calls against another component (e.g., the servlet calls a method in the session bean), the caller component never instantiates the callee component. Instead, the caller requests a reference (or “stub”) to the callee from the container using the callee’s interface. The container manages all the object creation and the components are only coupled by interfaces. The benefit is that when we change a component implementation, the effect of the change would not ripple out of the component itself as long as we keep its published interface stable.

    Shared services provided by the container:

    The J2EE container provides common application services, such as transaction management, network connection pools, access security, data persistence, and logging, to the components. That allows the application to focus on the business logic.

    Declarative configuration:

    In J2EE, you can simply configure how the container service is delivered to your components using XML configuration files. The use of metadata to configure services reduces the clutter in the code and makes J2EE components easier to maintain.

    A complete Object Relational Mapping (ORM) solution:

    You can use J2EE entity beans to model application data stored in a backend relational databases. That allows you to operate on Java objects instead of dealing with the relational model via SQL statements. The details of vendor-dependent SQL statements are generated by the container and are completely transparent to the application developer.

What is a Lightweight Framework

  • The “lightweight” component approach was originally proposed to counter the “heavyweight” approach in EJB 2.1
  •  EJB 2.1 is the core business component framework in J2EE 1.4, and it is notoriously hard to use
  • EJB3 is core to Java EE 5.0, and is an industry-wide effort to standardize a lightweight framework for Java enterprise developers.
  • EJB3 looks almost completely different from EJB 2.1, yet it captures the flexibility and power of the J2EE way.
  • (a)  POJOs as Components
  • (b) Annotation-based Metadata for Services Configuration
  • (c) Dependency Injection
  • (d) Extensible Container Services

Reference:

https://docs.jboss.org/books/lightweight/ch01.html

JSON parsing methods

1) Use JSONNode with ObjectMapper using mapper.readTree(jsonString)

  • eg: String jsonString = “{“name”:”superman”,”age”:”25″}”;

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode jsonNode1 = rootNode.get(“name”);

example reading from json file:

InputStream inputStream = ExampleStructure.class.
.getResourceAsStream(“example.json”);
JsonNode rootNode = mapper.readTree(inputStream);

//usage of path() in addition to usage of get()

rootNode.path(“address”).path(“country”).textValue();

More detailed example:

2) Use ObjectMapper and mapper.readValue(source_json, destination_pojo);

Screen Shot 2019-01-15 at 12.35.56 AM.png

Screen Shot 2019-01-15 at 12.37.11 AM.png

3) Use JSONObject(source_json) and destination is a  jsonObject.getJsonArray(“nodename”) etc

Screen Shot 2019-01-15 at 12.39.56 AM.png

FAQ )
So
readTree() for JSONNode and
readValue() for POJO?

No, you can use readValue() for JSONNode as well:

ie: JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class);

Additional properties

objectMapper.configure(
    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);

Java 8 lambdas usage:

https://stackoverflow.com/questions/38662582/update-json-values-with-lambda

JsonNode json = new ObjectMapper().readTree(new ObjectMapper().writeValueAsString(myObject));

ObjectNode rootNode = (ObjectNode) json;
ObjectNode resourceNode = (ObjectNode) rootNode.path("resource");
resourceNode.fields().forEachRemaining(
    entry -> resourceNode.set(
        entry.getKey(),
        func(entry.getValue())
    )
);

Java 8 Streams usage:

StreamSupport.stream(jn.spliterator(), false /* or whatever */);

linkedlist-collections.sort()

        LinkedList

  • LinkedList implements the java.util.List interface, so you can sort the LinkedList by using Collections.sort() method.
  • Since LinkedList class implements the linked list data structure which doesn’t provide random access based upon the index, sorting is quite expensive.
  • In order to access any element, you need to first traverse through that element which is O(n). 

    How Collections.sort() does sorting to avoid O(n) complexity?

  • Collections.sort() method uses an efficient strategy to handle this scenario.
  • It first copies the contents of LinkedList to an array, sorts the array and copies it back.
  • So it’s as efficient as sorting an ArrayList.

    About Collections.sort() ‘s  natural sorting/custom sorting ?


  • By default Collections.sort() arrange elements of linked list into their natural order of sorting
  • But it also accepts a Comparator, which can be used to sort elements in custom order.
  • Java 8 also introduced a new sort() method on the java.util.List interface itself, which means you no longer need Collections.sort() to sort a LinkedList, you can do directly by calling the LinkedList.sort() method in Java 8

 

Which is preferred? – Primitive datatypes or Autoboxing(Java primitives vs Objects comparison)?

Primitive datatypes and Autoboxing

  • Avoid creating objects(wrapper classes) unnecessary.
  • Prefer primitives.
  • Boxed types have poor performance and memory issues. It may also lead to NPE’s.
  • Read this for Java primitives vs Objects comparison and measuring their performance – https://www.baeldung.com/java-primitives-vs-objects

Order of execution of Static , Initializer and Constructor in a class with a parent class

What is the order of execution of Static , Initializer and Constructor in a class with a parent class eg: Class A extends Class B

Always remember the rule – “SIC” – Static, Initializer and then Constructor.

  1.  Parent class is loaded first
  2.  Static block of Parent
  3. Child class is loaded 
  4. Static variables/block of Child
  5. Initializer of Parent
  6. Constructor of Parent
  7.  Initializer of Child
  8. Constructor of Child

 

print something on console if there is no PSVM method

If your class doesn’t have a PSVM (main method), is there a way to print something on console?

Yes, use Static blocks.

  •  Static blocks is mostly used for changing the default values of static variables.
  • A static block gets executed when the class is loaded into memory
  •  A class can have multiple static blocks which will be executed in the order in which they are written.

Java System.out.println

System

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html

public final class System extends Object

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

out 

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out

public static final PrintStream out
The “standard” output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.

println 

https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println()

PrintStream.println() -> public void println()
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character (‘\n’).

 

Here’s a very good explanation of System.out.println

http://javapapers.com/core-java/system-out-println/

Quoting a few points

What is System.out.println

System.out.println is a Java statement that prints the argument passed, into the System.out which is generally stdout.

  • System – is a final class in java.lang package. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…
  • out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data.
  • println – is a method of PrintStream class. println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. printcalls write() and the story goes on like that.

 

System.out.println vs loggers like Log4j

Log4J has mulitple levels for logging. If we are writing a real short program, just for experimental/learning purposes SOPs are fine. When we are developing a production quality software, we should be aware that a logging component should be used and System.out.println should be avoided. Why?

  • Flexibility: a logger like log4j provides different levels for logging. We can separate the log messages accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.
  • Reconfigurability: in just one parameter change we can switch off all the logging statements.
  • Maintainability: imagine if we have hundreds of System.out.println littered all through the application, it would be difficult to maintain the program over a period.
  • Granularity: In an application, every single class can have a different logger and controlled accordingly.
  • Utility: Option for redirecting the message is limited in System.out, but in case of a logger you have appenders which provides numerous options. We can even create a custom output option and redirect it to that.

 

java finally with try catch – control flow use-cases

try-catch-finally is  a popular Java interview question

Q-1) Does Finally block always gets executed?

  • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise,
  • if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Q-2)  How is the flow of control with try-catch, try-catch-finally, try-finally when exception occurs on try catch ?

See below topic for all similar category questions on finally block control-flow.

Tip – If a statement in try block raised an exception, then the rest of the try block doesn’t execute and control passes to the corresponding catch block. After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed.

Flow of control in try-catch-finally in Java

    1. Control flow in try-catch clause OR try-catch-finally clause 

      1.1) try-catch  (when exception occurred & handled)
      1.2) try-catch-finally (when exception occurred & handled)
      1.3) 
      try-catch (when exception occurred & not-handled)
      1.4) 
      try-catch-finally (when exception occurred & not-handled)
      1.5) 
      try-catch (when exception not-occurred )
      1.6) 
      try-catch-finally (when exception not-occurred)

    2. try-finally clause 

      2.1) try finally (when exception occurred )
      2.2) try finally (when exception not-occurred )

      OK, Let’s start seeing all the scenarios:

       

      1.1) try-catch  (when exception occurred & handled)

       

      class Demo  
      {
      public static void main (String[] args) 
      {
      // array of size 4.
      int[] arr = new int[4];
      try
      {
      inti = arr[4]; // this will throw exception.
       
      System.out.println("Inside try block");
      }
      catch(ArrayIndexOutOfBoundsException ex)
      {
      System.out.println("Exception caught in Catch block");
      }
      System.out.println("Outside try-catch clause");
      }
      }

      Output:

      Exception caught in Catch block
      Outside try-catch clause
      
      

      1.2) try-catch-finally (when exception occurred & handled)

      class Demo
      {
          public static void main (String[] args) 
          {
               
              // array of size 4.
              int[] arr = new int[4];
               
              try
              {
                  int i = arr[4]; // throws exception
                        
                  System.out.println("Inside try block");
              }
               
              catch(ArrayIndexOutOfBoundsException ex)
              {
                  System.out.println("Exception caught in catch block");
              }
               
              finally
              {
                  System.out.println("finally block executed");
              }
               
              System.out.println("Outside try-catch-finally clause");
          }
      }

      Output:

      Exception caught in catch block
      finally block executed
      Outside try-catch-finally clause
      



      1.3)  try-catch
      (when exception occurred & not-handled)

      class Demo  
      {
          public static void main (String[] args) 
          {
               
              // array of size 4.
              int[] arr = new int[4];
              try
              {
                  int i = arr[4]; // throws exception
                  System.out.println("Inside try block");
              }
               
              // This is not catching the actual exception.
      // This is as good as not defined a catch block.
              catch(NullPointerException ex)
              {
                  System.out.println("Exception has been caught");
              }
               
              System.out.println("Outside try-catch clause");
          }
      }

      Run Time Error:

      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
          at Demo.main(Demo.java:12)
      

      1.4) try-catch-finally (when exception occurred & not-handled)

      class Demo
      {
          public static void main (String[] args) 
          {
               
              // array of size 4.
              int[] arr = new int[4];
               
              try
              {
                  int i = arr[4]; // throws exception
                  System.out.println("Inside try block");
              }
               
              // not an appropriate handler
              catch(NullPointerException ex)
              {
                  System.out.println("Exception has been caught");
              }
               
              finally
              {
                  System.out.println("finally block executed");
              }
               
              System.out.println("Outside try-catch-finally clause");
          }
      }

      Output :

      finally block executed
      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
          at Demo.main(Demo.java:12)

      1.5)  try-catch (when exception not-occurred )

      class Demo
      {
          public static void main (String[] args)
          {
               
              try
              {
                   
                  String str = "123";
                       
                  int num = Integer.parseInt(str);
                       
                  // note that there was no exception thrown
                  System.out.println("Inside try block");
                   
              }
               
              catch(NumberFormatException ex)
              {
                       
                  System.out.println("catch block executed...");
                       
              }
       
              System.out.println("Outside try-catch clause");
          }
      }

      Output :

      Inside try block
      Outside try-catch clause
      

      1.6) try-catch-finally (when exception not-occurred)

      class Demo
      {
          public static void main (String[] args)
          {
               
          try
          {
               
              String str = "123";
                   
              int num = Integer.parseInt(str);
                   
              // Note that there was no exception thrown.
              System.out.println("try block fully executed");
               
          }
           
          catch(NumberFormatException ex)
          {
                   
              System.out.println("catch block executed...");
                   
          }
           
          finally
          {
              System.out.println("finally block executed");
          }
       
          System.out.println("Outside try-catch-finally clause");
          }
      }

      Output :

      try block fully executed
      finally block executed
      Outside try-catch clause
      

2) try finally

  • no matter whether an exception occur in try-block or not, finally will always be executed.
  • But control flow will depend on whether exception has occurred in try block or not.

    2.1) try finally (when exception occurred )

     

    class Demo
    {
        public static void main (String[] args) 
        {
             
            // array of size 4.
            int[] arr = new int[4];
            try
            {
                int i = arr[4];
                     
                //Exception was thrown by above line.
                System.out.println("Inside try block");
            }
             
            finally
            {
                System.out.println("finally block executed");
            }
             
            // rest of the program will NOT be executed
            System.out.println("Outside try-finally clause");
        }
    }

    Output :

    finally block executed
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
        at Demo.main(Demo.java:12)
    
    

    2.2) try finally (when exception not-occurred )

    class Demo  
    {
        public static void main (String[] args) 
        {
             
            try
            {
                String str = "123";
                 
                int num = Integer.parseInt(str);
                 
                // Note that exception was NOT thrown
                System.out.println("Inside try block");
            }
             
            finally
            {
                System.out.println("finally block executed");
            }
             
            // rest program will be executed
            System.out.println("Outside try-finally clause");
        }
    }
    Output :
    Inside try block
    finally block executed
    Outside try-finally clause
    

JavaStreamUsageWithMapReduce- code snippet

JavaStreamUsageWithMapReduce- code snippet

Olderposts

Copyright © 2020 Codinko- Java Coding Tutorials

Theme by Anders NorenUp ↑