Sunday, November 29, 2015

Dependecy Injection

Dependecy Injection ;
1. Dependency injection is a style of object configuration in which an objects fields and collaborators are set by an external entity. In other words objects are configured by an external entity. Dependency injection is an alternative to having the object configure itself.

The Person class itself instantiates a Name as its Name implementation. Therefore the Person class is said to "satisfy its own dependencies". When a class satisfies its own dependencies it automatically also depends on the classes it satisfies the dependencies with. In this case Person now also depends on Name , and on the three hardcoded string values passed as parameter to the Person constructor. You cannot use a different value for the four strings, nor use a different implementation of the Name interface, without changing the code.

public class Person{

    protected Name name=
    new Name("firstName", "middleName", "lastName");

    //data access methods...
    public Person readPerson(int primaryKey) {...}

  }

As you can see, when a class satisfies its own dependencies it becomes inflexible with regards to these dependencies. This is bad. This means, that if you need to change the dependencies you will have to change the code. 

Let's change the design a little:

public class Person {

  protected Name name= null;

  public Person(String firstName, String middleName, String lastName){
    this.name= new Name(firstName, middleName, lastName);
  }


  //data access methods...
  public Person readPerson(int primaryKey) {...}

}
Notice how the Name instantiation is moved into a constructor. The constructor takes three parameters which are the four values needed by the Name. Though the Person class still depends on these three values, it no longer satisfies these dependencies itself. They are provided by whatever class creating a Name instance. The values are said to be "injected" into the Person constructor. Hence the term "dependency injection".



Dependency injection is not restricted to constructors. You can also inject dependencies using setter methods, or directly into public fields.


public class Person{

    protected Name name= null;
    
    public Person(Name name){
      this.name = name;
    }

    
    //data access methods...
    public Person readPerson(int primaryKey) {...}

  }
If all components in your system have their dependencies injected, somewhere in the system some class or factory must know what to inject into all these components. This what a dependency container does. The reason it is called a container and not a factory is that the container often takes on more responsibility than just instantiating objects and injecting dependencies.



If some components are configured as singletons some containers are able to call methods on the singleton when the container is shut down. That way the singleton can release any resources it may hold, like database or network connections. This is often referred to as "instance life cycle management". This means that the container is capable of managing the component throughout the various stages of the components life cycle. For instance, instantiation, configuration and disposal.

 The fact that the container sometimes keep a reference to the components after instantiation is the reason it is called a "container", and not a factory. Dependency injection containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object. Otherwise the garbage collector would have a hard time collecting all these objects when no longer used.



There are several dependency injection containers available.  Spring, Pico Container, Guice, and others.


There are several benefits from using dependency injection containers rather than having components satisfy their own dependencies. Some of these benefits are:
  • Reduced Dependencies
  • Reduced Dependency Carrying
  • More Reusable Code
  • More Testable Code
  • More Readable Code



More specifically, dependency injection is effective in these situations:
  • You need to inject configuration data into one or more components.
  • You need to inject the same dependency into multiple components.
  • You need to inject different implementations of the same dependency.
  • You need to inject the same implementation in different configurations.
  • You need some of the services provided by the container.
These situations have one thing in common. They often signal that the components wired together represent different or independent concepts or responsibilities, or belong to different abstraction layers in the system. For instance, database configuration (driver, url, user, password) and a DataSource implementation are different concepts. Similarly a DataSource and a DAO class represent different concepts and belong to different abstraction layers.




Dependency injection is not effective if:
  • You will never need a different implementation.
  • You will never need a different configuration.
If you know you will never change the implementation or configuration of some dependency, there is no benefit in using dependency injection.



Difference Between Factory Design Pattern and DI

The Purpose of the Factory Design Patterns

The purpose of the factory patterns is to separate the use of a certain component, from the choice of implementation + instance management of that component. These three separate concerns are repeated here:
  • Component Use
  • Component Implementation Choice
  • Component Instance management

Wednesday, November 25, 2015

Spring Notes : 1

:

//1.BASICS OF SPRING
1.Spring does many things. But at the root of
almost everything Spring provides are a few foundational ideas, all focused on
Spring’s fundamental mission: Spring simplifies Java development.

2.To back up its attack on Java complexity, Spring employs four key strategies:
 Lightweight and minimally invasive development with POJOs
 Loose coupling through DI and interface orientation
 Declarative programming through aspects and common conventions
 Eliminating boilerplate code with aspects and templates

3.Spring avoids (as much as possible) littering your application code with its API.
Spring almost never forces you to implement a Spring-specific interface or extend a
Spring-specific class. Instead, the classes in a Spring-based application often have no
indication that they’re being used by Spring. At worst, a class may be annotated with
one of Spring’s annotations, but it’s otherwise a POJO.

//2.HOW DI WORKS
Traditionally, each object is responsible for obtaining its
own references to the objects it collaborates with (its dependencies). This can lead to
highly coupled and hard-to-test code.
The act of creating associations between application components is commonly
referred to as wiring.

In a Spring application, an application context loads bean definitions and wires them
together. The Spring application context is fully responsible for the creation of and
wiring of the objects that make up the application. Spring comes with several implementations
of its application context, each primarily differing only in how it loads its
configuration.

//3.WHAT IS ASPECTS .Aspects
Although DI makes it possible to tie software components together loosely, aspectoriented
programming (AOP) enables you to capture functionality that’s used
throughout your application in reusable components.
AOP is often defined as a technique that promotes separation of concerns in a software
system. Systems are composed of several components, each responsible for a specific
piece of functionality. But often these components also carry additional responsibilities
beyond their core functionality. System services such as logging, transaction
management, and security often find their way into components whose core responsibilities
is something else. These system services are commonly referred to as cross-cutting
concerns because they tend to cut across multiple components in a system


6.
AOP makes it possible to modularize these services and then apply them declaratively
to the components they should affect. This results in components that are more cohesive
and that focus on their own specific concerns, completely ignorant of any system
services that may be involved. In short, aspects ensure that POJOs remain plain.

7.
In a Spring-based application, your application
objects live in the Spring container.
As illustrated in figure 1.4, the container
creates the objects, wires them together,
configures them, and manages their complete
lifecycle from cradle to grave (or new
to finalize(), as the case may be).


8.
The container is at the core of the Spring Framework. Spring’s container uses DI to
manage the components that make up an application. This includes creating associations
between collaborating components. As such, these objects are cleaner and easier
to understand, they support reuse, and they’re easy to unit test.
There’s no single Spring container. Spring comes with several container implementations
that can be categorized into two distinct types. Bean factories (defined by
the org.springframework.beans.factory.BeanFactory interface) are the simplest
of containers, providing basic support for DI. Application contexts (defined by the
org.springframework.context.ApplicationContext interface)

//4.APPLICATION CONTEXT
Working with an application context
Spring comes with several flavors of application context. Here are a few that you’ll
most likely encounter:
 AnnotationConfigApplicationContext—Loads a Spring application context
from one or more Java-based configuration classes
 AnnotationConfigWebApplicationContext—Loads a Spring web application
context from one or more Java-based configuration classes
 ClassPathXmlApplicationContext—Loads a context definition from one or
more XML files located in the classpath, treating context-definition files as classpath
resources
 FileSystemXmlApplicationContext—Loads a context definition from one or
more XML files in the filesystem
 XmlWebApplicationContext—Loads context definitions from one or more

XML files contained in a web application


10. //5.BEANS LIFE CYCLE
A bean’s life
Java’s new keyword is
used to instantiate the bean, and it’s ready to use. Once the bean is no longer in use,
it’s eligible for garbage collection and eventually goes to the big bit bucket in the sky.






Let’s break down figure 1.5 in more detail:
1 Spring instantiates the bean.
2 Spring injects values and bean references into the bean’s properties.
3 If the bean implements BeanNameAware, Spring passes the bean’s ID to the set-
BeanName() method.
4 If the bean implements BeanFactoryAware, Spring calls the setBeanFactory()
method, passing in the bean factory itself.
5 If the bean implements ApplicationContextAware, Spring calls the set-
ApplicationContext() method, passing in a reference to the enclosing application
context.
6 If the bean implements the BeanPostProcessor interface, Spring calls its post-
ProcessBeforeInitialization() method.
7 If the bean implements the InitializingBean interface, Spring calls its after-
PropertiesSet() method. Similarly, if the bean was declared with an initmethod,
then the specified initialization method is called.
8 If the bean implements BeanPostProcessor, Spring calls its postProcess-
AfterInitialization() method.
9 At this point, the bean is ready to be used by the application and remains in the
application context until the application context is destroyed.

10 .If the bean implements the DisposableBean interface, Spring calls its
destroy() method. Likewise, if the bean was declared with a destroy-method,
the specified method is called.


//6.SPRING REQUIRED LIB
As of Spring 4.0, there
are 20 distinct modules in the Spring
Framework distribution, with three JAR
files for each module




//7.SPRING ARCHITECHTURE





//8. SPRING 3.1 FEATURES
What was new in Spring 3.1?
Spring 3.1 had several useful new features and improvements, many of which were
focused on simplifying and improving configuration. In addition, Spring 3.1 provided
declarative caching support as well as many improvements to Spring MVC. Here’s a
brief list of some of the highlights of Spring 3.1:
 To address the common issue of selecting distinct configurations for various
environments (such as development, test, and production), Spring 3.1 introduced
environment profiles. Profiles make it possible, for instance, to select a
different data source bean depending on which environment the application is
deployed in.
 Building on Spring 3.0’s Java-based configuration, Spring 3.1 added several enable
annotations to switch on certain features of Spring with a single annotation.
 Declarative caching support made its way into Spring, making it possible to
declare caching boundaries and rules with simple annotations, similar to how
you could already declare transaction boundaries.


A new c namespace brought constructor injection the same succinct attributeoriented
style as Spring 2.0’s p namespace brought to property injection.
 Spring began to support Servlet 3.0, including the ability to declare servlets and
filters in Java-based configuration instead of web.xml.
 Improvements to Spring’s JPA support made it possible to completely configure
JPA in Spring without needing a persistence.xml file.
Spring 3.1 also included several enhancements to Spring MVC:
 Automatic binding of path variables to model attributes
 @RequestMappingproduces and consumes attributes, for matching against a
request’s Accept and Content-Type headers
 A @RequestPart annotation that enables binding parts of a multipart request to
handler method parameters
 Support for flash attributes (attributes that survive a redirect) and a Redirect-
Attributes type to carry the flash attributes between requests



//9/SPRING 3.2 FEATURES
What was new in Spring 3.2?
Whereas Spring 3.1 was largely focused on configuration improvements with a small set
of other enhancements, including Spring MVC enhancements, Spring 3.2 was primarily
a Spring MVC-focused release. Spring MVC 3.2 boasted the following improvements:
 Spring 3.2 controllers can take advantage of Servlet 3’s asynchronous requests
to spin off request processing in separate threads, freeing up the servlet thread
to process more requests.
 Although Spring MVC controllers have been easily testable as POJOs since
Spring 2.5, Spring 3.2 included a Spring MVC test framework for writing richer
tests against controllers, asserting their behavior as controllers, but without a
servlet container.
 In addition to improved controller testing, Spring 3.2 included support for
testing RestTemplate-based clients without sending requests to the real REST
endpoint.
 An @ControllerAdvice annotation enables common @ExceptionHandler,
@InitBinder, and @ModelAttributes methods to be collected in a single class
and applied to all controllers.
 Prior to Spring 3.2, full content negotiation support was only available via
ContentNegotiatingViewResolver. But in Spring 3.2, full content negotiation
became available throughout Spring MVC, even on controller methods relying
on message converters for content consumption and production.
 Spring MVC 3.2 included a new @MatrixVariable annotation for binding a
request’s matrix variables to handler method parameters.
 The abstract base class AbstractDispatcherServletInitializer can be used
for conveniently configuring DispatcherServlet without web.xml. Likewise, a
subclass named AbstractAnnotationConfigDispatcherServletInitializer
can be used when you wish to configure Spring with Java-based configuration.
 The ResponseEntityExceptionHandler class was added to be used as an alternative
to DefaultHandlerExceptionResolver. ResponseEntityException-
Handler methods return ResponseEntity instead of ModelAndView.
 RestTemplate and @RequestBody arguments support generic types.
 RestTemplate and @RequestMapping methods support the HTTP PATCH
method.
 Mapped interceptors support URL patterns to be excluded from interceptor
processing.



//10. SPRING 4.0 FEATURES
What’s new in Spring 4.0?
Spring 4.0 is the freshest release of Spring available. There are a lot of exciting new
features in Spring 4.0, including the following:
 Spring now includes support for WebSocket programming, including support
for JSR-356: Java API for WebSocket.
 Recognizing that WebSocket offers a low-level API, screaming for a higher-level
abstraction, Spring 4.0 includes a higher level message-oriented programming
model on top of WebSocket that’s based on SockJS and includes STOMP subprotocol
support.

A new messaging module with many types carried over from the Spring Integration
project. This messaging module supports Spring’s SockJS/STOMP support.
It also includes template-based support for publishing messages.
 Spring 4.0 is one of the first (if not the first) Java frameworks to support Java 8
features, including lambdas. Among other things, this makes working with certain
callback interfaces (such as RowMapper with JdbcTemplate) much cleaner
and easier to read.
 Along with Java 8 support comes support for JSR-310: Data and Time API, offering
the opportunity for developers to work with dates and times in a richer API
than that offered with java.util.Date or java.util.Calendar.
 A smooth programming experience for applications developed in Groovy has
also been added, essentially enabling a Spring application to be developed easily
entirely in Groovy. With this comes the BeanBuilder from Grails, enabling
Spring applications to be configured with Groovy.
 Generalized support for conditional bean creation has been added, wherein
beans can be declared to be created only if a developer-defined condition is
met.
 Spring 4.0 also includes a new asynchronous implementation of Spring’s Rest-
Template that returns immediately but allows for callbacks once the operation
completes.
 Support for many JEE specs has been added, including JMS 2.0, JTA 1.2, JPA 2.1,
and Bean Validation 1.1.



TODO



Tuesday, May 12, 2015

When to use Interfaces and when o use Abstract Classes

When to use Interfaces and when o use Abstract Classes


 I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.

Abstract Classes
1.Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.
2.Define abstract member signatures that base classes must implement.
3.Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.
4.Can include data stored in fields.
5.Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.
6.Deriving from an abstract class uses up a subclass's one and only base class option.
Interface
1.Cannot be instantiated.
2.Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.
3.Extending interfaces with additional members breaks the version compatibility.
4.Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.
5.All members are automatically virtual and cannot include any implementation.
6.Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.

Encapsulation Java

Encapsulation Java

We always say that data will be encapsulated if we simply define variables private and define getters setters to access those variables. My question is if we can access the variables (data) though via getters and setters, how come data is hidden or safe?

There are a couple of things comes under encapsulation.
  1. Contract Management: If you make itpublic, you are literally making anyone to change it to whatever they want. You can't protect it by adding a constraint. Your setter can make sure, data gets modified in an appropriate way.
  2. Mutability: You do not always have to have a setter. If there is a property that you wanted to keep immutable for the life span of the object. You just make it private and have no setter for it. It will probably be set via constructor. Then your getter will just return the attribute (if it's immutable) or a copy of the attribute (if attribute is mutable).

in general encapsulation of fields by getters and setters leaves more flexibility for changes.
If fields are accessed directly you are stuck with "stupid fields". Fields can only be written and read. Nothing else can be done while accessing a field.
When using methods you can do whatever you want while setting / reading the value. As markus and Jigar mentioned validation is possible. In addition you could decide some day, that the value is derived from another value or some actions must be executed if the value changes.
how come data is hidden or safe
Data is neither hidden nor safe by using getters and setters. It just gives you the possibility to make it safe. What is hidden is the implementation and not the data.

Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.
The beauty of encapsulation is the power of changing things without affecting its users.
In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).
Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.
The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.
There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:
  • You can limit the values that can be stored in a field (i.e. gender must be F or M).
  • You can take actions when the field is modified (trigger event, validate, etc).
  • You can provide thread safety by synchronizing the method.
  • You can switch to a new data representation (i.e. calculated fields, different data type)
However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.

The Beauty of Encapsulation

Now, in my opinion, to really understand encapsulation, one must first understand abstraction.
Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a break system, a fuel system, etc.
However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.
However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users where interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.
Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.
So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.
I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.

Wednesday, May 6, 2015

Spring related questions

Spring related questions
1. what is ioc ? its type ? need of ioc ?
2.bean  autowire types
           -no , byName ,byType , constructor , autodetect
3.bean abstract=true
4. bean id ? mutliple Ids , names
5. scopes of beans - session , requet , global.session , prototype , singleton
6.singleton with multiple proptotype refrences
7.singleton beans are thread safe
8. prototype with mutliple sington instance
9. bean life cycle ? overrding setup and teardown
10.init and destroy methods
11 .what is lazy init
12. innerbean and calling inner bean from outside
13.loading propertiesfile
14.message resource
15.referring Collections in beans
16. spring qualifier
17.  @Autowired @Resource @PostConstruct @PreDestroy @Qualifier @Required @Bean @Component @Service @Repository   @Configuration   @DependsOn   @Primary  @Lazy  @Import  @ImportResource   @Value

18. : Tells Spring framework to read @Transactional annotation\
19/ : Automatically adds transaction support which eventually wraps your code in transaction scope
20. uploading file in spring - multipatresolver





Sunday, April 26, 2015

INTRO

1. TECHNOLOGIES
      1. JAVA
      2.DATABASE
      3.DESIGN PATTERNS
      4.DATA STRUCTURE AND ALGORITHM
2.FRAMEWORKS
       1. SPRING - MVC CORE SECURITY AND BOOT  
       2.MAVEN
       3.HIBERNATE

8.PUZZLES 




1.CONCEPT 
2. INTERVIEW QUESTIONS RELATED TO CONCEPT AND ITS ANSWERS
3.PROGRAM RELATED TO IT AND SOLUTIONS
4.SAMPLE PROJECTS RELATED TO CONCEPT 




Abstraction in java

Abstraction
Abstraction is the technique of hiding implementation. At it's core there's not much more to that answer. The bulk of meaning to abstraction come from how and why it is used.
It is used for the following scenarios
  • Reduce complexity. (Create a simple interface)
  • Allow for implementation to be modified without impacting its users.
  • Create a common interface to support polymorphism (treating all implementations of the abstracted layer the same.
  • Force users to extend the implementation rather than modify.
  • Support cross platform by changing the implementation per platform.

Quite simply, abstraction is the art of limiting your dependencies. The less you depend on, the more abstract you are.

Abstraction is the ability to work with the high-level concept while ignoring low-level details

Abstraction is "To represent the essential feature without representing the back ground details."

Its a concept of defining an idea in terms of classes or interface 

Encapsulation 

Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. 



Important points about encapsulation in Java.

1. "Whatever changes encapsulate it" is a famous design principle.
2. Encapsulation helps in loose coupling and high cohesion of code.
3. Encapsulation in Java is achieved using access modifier private, protected and public.
4. Factory pattern , Singleton pattern in Java makes good use of Encapsulation.