Saturday, April 13, 2019

Angular Quiz



Score :
0
Test your understanding
angular-cli.json was deprecated in which version ?
v5
v4
v6
v7
Info

Sunday, March 31, 2019

core.js:1673 ERROR Error: Uncaught (in promise): TypeError: instance[output.propName].subscribe is not a function

Hi Guys ,



Today I have faced this error :

core.js:1673 ERROR Error: Uncaught (in promise): TypeError: instance[output.propName].subscribe is not a function

Later I have found out that I have imported the EventEmitter from a different package in my component file :

import { EventEmitter } from 'events';


Later when I changed the package to @angular/core it worked fine .


import { EventEmitter } from '@angular/core';

The full stack trace is below for your reference :





ERROR Error: Uncaught (in promise): TypeError: instance[output.propName].subscribe is not a function
TypeError: instance[output.propName].subscribe is not a function
    at createDirectiveInstance (core.js:9183)
    at createViewNodes (core.js:10399)
    at callViewAction (core.js:10715)
    at execComponentViewsAction (core.js:10634)
    at createViewNodes (core.js:10427)
    at createRootView (core.js:10313)
    at callWithDebugContext (core.js:11344)
    at Object.debugCreateRootView [as createRootView] (core.js:10831)
    at ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:8659)
    at ComponentFactoryBoundToModule.push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create (core.js:3311)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:3811)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)
defaultErrorLogger @ core.js:1673
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1719
next @ core.js:4311
schedulerFn @ core.js:3551
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3535
(anonymous) @ core.js:3842
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3779
onHandleError @ core.js:3842
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:395
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:164
_loop_1 @ zone.js:694
api.microtaskDrainDone @ zone.js:703
drainMicroTaskQueue @ zone.js:608
Promise.then (async)
scheduleMicroTask @ zone.js:584
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:413
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:238
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @ zone.js:258
scheduleResolveOrReject @ zone.js:879
ZoneAwarePromise.then @ zone.js:1012
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js:4345
./src/main.ts @ main.ts:11
__webpack_require__ @ bootstrap:76
0 @ main.ts:12
__webpack_require__ @ bootstrap:76
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1










Saturday, March 30, 2019

ERROR Error: Uncaught (in promise): Error: Cannot match any routes.


Hi Guys ,

Today I have faced this error :

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. 

We will face this error when we enter the URL of the angular app and the URL does not have a matching route configured . To verify that check your AppModule or AppRoutingModule . 

1. check the router array :


const appRoutes:Routes =[
{path:'cust-detail',component: CustDetailComponent},
{path:'mcq',component: MCQComponent},
{path:'sign-up',component: SignUpComponent}
];


if the path is missing add to it .

2. check the import array :
imports: [
BrowserModule,
  FormsModule,
  ReactiveFormsModule,
  RouterModule.forRoot(appRoutes),
],

You need to have the RouterModule.forRoot(appRoutes) present in your application.

The full stack trace is below for your reference :


ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'test'
Error: Cannot match any routes. URL Segment: 'test'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:1384)
    at CatchSubscriber.selector (router.js:1365)
    at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:80)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (Subscriber.js:60)
    at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._error (tap.js:61)
    at resolvePromise (zone.js:831)
    at resolvePromise (zone.js:788)
    at zone.js:892
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:3811)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at drainMicroTaskQueue (zone.js:601)

Thursday, March 21, 2019

Web services Interview Questions

Web Services Interview Questions.
This blog is just for revision.
  • What is SOAP Web Services
SOAP ( simple object access protocol) based web services (application exchange information over network)  .
  • What is Contract first ?
WSDL or XSD is created first , then the java classes .

  • What is WSDL ?
WS Description Language , it describes a web service .
  • What are the parts of wsdl ?
  1. types : data types used 
  2. message : request and response
  3. portType : operations available
  4. binding : 
  5. Operations:
  6. Service :
Types
Schema
Contract namespace
Schema location xsd

Message can be multiple
Part
Name
Element
Type


Port type
Operation
Input, output,fault



Binding
Style document/ RPC transport
Operation
Input
Header, body
Output
Header,body
Fault
Fault


Service
Port
Binding
Location
  • What is XSD ?
It defines schema which defines structure of xml.


  • Explain wsdl2java

Use pluggin cfx-codegen-pluggin
Goal wsdl2java
Wsdl location
Binding files
Note : wsdl will have xsd,a java class for each xsd will be generated.



  • What are the elements of soap message?


  1. Envelope
  2. Header
  3. Body
  4. Fault


  •  What are SOLID principles in Rest Web services Development ?
  1. Single Responsibility : Each class has only one function 
  2. Open for Extension Closed for Modification : existing classes should not be modified , instead new classes should be created .
  3. Liskov Substitution Principle :  App should work fine if we substitute subclass in place of super class .
  4. Interface Segregation : large interfaces should be divided into smaller ones .
  5. Dependency Inversion : loose coupling .

Wednesday, March 20, 2019

Hibernate interview questions

This blog is just for revision .
  • What is ORM ?
Object Relational Mapping : Object to database tables .
  • Explain Core Classes in hibernate .
  1. Configuration : load xml file .
  2. SessionFactory : thread safe
  3. Session : get connection with database , not thread safe , used to perform CRUD operations .
  4. Transaction :  commit and rollback operations . unit of work.
  5. Query : common query language for any type of database.
  6. Criteria : add restrictions and projections
  • Explain Hibernate configuration file 
contains database details used to initialize session factory .

  • Explain Hibernate Mapping file 
contains table and column details also contains the entity bean mapping .

  • Explain state of the entity in the persistence context .
Session is the persistence context which is used to manage relationship of the entities .
  1. transient : newly created object 
  2. persistent : associated with session ( session.save)
  3. detached : session closed 
  • How to use hibernate in spring ?
In application context.xml file specify

  1. the datasource bean  DriverManagerDataSource  
    • specify the username /password or jndi
  2. sessionfactory bean LocalSessionFactoryBean
  3. transaction bean HibernateTransactionManager
  4. tx:annotation driven 
  • What is hibernate dialect.
Different dialect for different databases
MySqlDialect , Oracle Dialect ,Db2 Dialect.


  • What are the different consistency anomalies in hibernate .
  1. dirty read .reading uncommitted data
  2. non repeatable read : second read returns different values for a row
  3. phantom read : second read returns different number of rows 

  • Explain isolation level .
  1. Read uncommitted
  2. Read committed :  
      4. Repeatable Read : second read will return same value 
      8. synchronized : does not allow concurrency

Isolation level is set using property hibernate.connection.isolation 


  • Explain the locking strategy based on isolation level .
  1. Read uncommitted : no lock 
  2. Read committed : lock on committed data
      4. Repeatable Read : lock on a block of  SQL
      8. Synchronized : full lock on table .

  • In which scenario repeatable read will return different data .
If the read is based on a condition and another thread inserts a row in database . Now for the second read we may get the new also if it satisfies the condition .
  • What is Caching in hibernate ?
  1. First level Catch : session cache of hibernate , enabled by default 
  2. Second Level Cache : optional , eg : Ehcache 
  3. Query Level Cache : cached query results . set hibernate.cache.use_query_cache property to true
  • What are the concurrency strategies for second level cache?
  1. Transactional : synchronized with the database .
  2. Read-write : if the transaction is not committed , the entity is fetched from database and referred from the cache .
  3. non strict read write : cache updated after data committed
  4. read only : used when data never gets changed .

  • What is dirty checking?

When hibernate loads an entity it keeps a copy of it in the memory, on tx.commit it compares the entity and the copy . If there are any changes, update statement is executed in the database.
  • Explain session.get
  1. Hits the database immediately.
  2. If record is not available in the database it returns null.
  • Explain session.load
  1. Returns proxy object without hitting the database.
  2. If the record is not available and when we try to access it through the proxy object we get Object Not Found Exception.
  • What is the difference between get and load ?
in case of no records in the database get returns null and load throws an exception .
  • What is the difference between save and persist ?
save return the id and persists returns nothing .persist marks the entity as persistent , does not generate Insert statement outside transaction boundaries . session.save on detached object will create a new row , session.persist on detached object will throw persistentobjectexception.

What is the difference between session.save and session.saveorupdate
save will insert the record if the Id is not available and throw exception if the Id is available. Saveorupdate will insert the record if the Id is not available, else it will update it.


  • What is the difference between update and merge ?
Update is used to update the persistent entity and Merge is used to update a detached entity .
  • What is the difference between session.flush and transaction.commit ?
flush synchronizes the persistent store with the state held  in memory .
commit commits the record to the database .
  • Explain Criteria
Used to filter record
cr =Session.createCriteria
cr.list();

  • Explain Restrictions
Used to add condition s to the query to compare the columns
Cr.add( Restrictions.eq("id" , 10));
  • Explain Projections
Used to call an aggregate method . Min , max , count .
Cr.setProjection( Projections.max("id"));

  • What is Declarative transaction management  ?
 transaction handling is not a part of business logic . 
using @Transactional :
  • What is Programmatic transaction management ?
transaction management is a part of business logic . 

  • Explain Different transaction manager used in spring .
  1. DataSourceTransactionManager : uses datasource 
  2. HibernateTransactionManager : uses sessionfactory
  3. JpaTransactionManager : uses entitiymanagerfactory 
  • Explain transaction propagation ?
using @Transactional( propagation=Propagation.
  1. REQUIRED : (default) if transaction is available use it otherwise create a new one. 
  2. REQUIRES_NEW : create a new transaction , commit / rollback is independent .
  3. NESTED : uses outer transaction but creates a savepoint to allow partial rollback and commit .

  • What is readOnly in @Transactional ?
used for only read operations
  • What are Value Types .
  1. Basic 
  2. Composite / Embedded
  3. Collection : for one to many .
  • Explain Many to Many .
Tables : Person , Project, PersonProject 
Entities :
Person : on projects set attribute add
  1. @ManyToMany 
  2. @JoinTable ( name=PersonProject , joinColums=@JoinColum , inverseJoinColumns=@JoinColum  )
Project: on persons set attribute add

  1.  @ManyToMany(mappedBy = "projects")


  • Explain One to Many
Tables : Person , Address

Entities :

  •   Explain Cascade type :
In case of mapping like one to one,or one to many , cascade type defines how changes in the entity will cascade to the mapped entity .
@ oneToMany cascade = Cascade Type.ALL
  1. All
  2. Persist
  3. Merge
  4. Refresh
  5. Remove
  6. Detach

  • How to lazy load the mapped classes

@oneToMany fetch = Fetch type.Lazy


  • What are the fetching strategies ?
  1. Join Fetching 
  2. Select Fetching 
  3. Sub select Fetching 
  4. Batch Fetching 

  • How to handle multiple databases ?
  1. @Table (schema= "")
  2. create two sessionfactory , use @Qualifier
  • How to handle distributed databases ?
use XA datasource , if  transaction is failed in one database , the entire transaction is roll backed .


  • What is the difference between jdbc and JTA?

2 phase commit can be handled using JTA only .

  •  Explain different ways of creating  EntityManager ?
  1. Container Managed : 
@PersistenceContext
EntityManager entityManager; 

2. Application Managed 
EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.model.student");
  • Explain  Anomalies in DBMS

1. Update : multiple rows needs to be updated to update a data .

2. Insert : cannot insert a row without supplementary data.

3. Delete : unable to delete a data as this will cause the important information to be deleted.



  • Explain normalization.

Normalization is a process of organizing the data in database to avoid data redundancy, insertion anomaly, update anomaly & deletion anomaly.
Terminology :
1. attribute : column
2. candidate key : primary key ( simple or composite )
3. prime attribute : column which is part of primary key
4. non prime attribute : column not part of primary key .
5. super key : any set of attributes which identifies a unique record .
6. functional dependency : B depends on A 
7. transitive dependency : B is dependent of A . C is dependent of B . So C has a transitive dependency on A .

1NF : attribute should be atomic.
2NF : non prime attribute should not depend on a subset of primary key
3NF : non prime attribute should not have transitive dependency with the super key .
BCNF : any functional dependency should be a super key .

Java interview questions

Most Common Java interview questions

  • String vs StringBuffer vs StringBuilder 
  1. String : immutable 
  2. StringBuffer : mutable , synchronized
  3. StringBuilder : mutable , not tread safe .

  • Explain toString method.

getClass().getName() + '@' + Integer.toHexString(hashCode())


  • Explain hashcode

it is a native method in object Class , returns integer code .
Two unequal objects can have same hashcode


  • Explain finalize

called before Garbage Collection .
  • How to create a immutable class ?
  1. make the class as final
  2. attributes as private and remove setters .
  3. getters should return a copy of object .
  • what is transient ?
Transient attributes are not serialized .
  • What is volatile ?
Changes made by one thread is immediately reflected on other thread .

  • What is static inner class 
  1. can be accessed without creating object of outer class , does not have access to instance variables .
  • What is Stack
    LIFO 
    1. push : add element on the top of stack
    2. pop : remove element from the top of stack
    3. peek : returns element at top of stack without removing it .
  • What is Queue 
FIFO .
  1. add : adds to last , in case of capacity restriction throws IllegalStateException.
  2. remove : returns and remove the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  3. element : returns the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  4. offer :  adds to last , in case of capacity restriction returns false .
  5. poll: returns and remove the element on the top of the queue , returns null if the queue is empty 
  6. peek: returns  the element on the top of the queue , returns null if the queue is empty .
  • What is Dqueue ?
supports insertion and removal from both ends .
  1. push  (addFirst)  : add element on the top of stack
  2. pop : remove element from the top of stack
  3. peek : returns element at top of stack without removing it .
  4. add : adds to last , in case of capacity restriction throws IllegalStateException.
  5. remove : returns and remove the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  6. element : returns the element on the top of the queue , throws NoSuchElementException if the queue is empty .
  7. offer :  adds to last , in case of capacity restriction returns false .
  8. poll: returns and remove the element on the top of the queue , returns null if the queue is empty 
  9. peek: returns  the element on the top of the queue , returns null if the queue is empty .

  • What is the difference between ArrayList and Vector?
Vector increase of capacity by double of its current capacity , ArrayList increase its capacity by 50%.
  • What is the difference between ArrayList and LinkedList ?
  1. LinkedList implements Dqueue has additional methods .
    1. decendingIterator
    2. getFirst
    3. getLast
    4. addFirst
    5. addLast
  2. Add and remove is faster , get and set is slower in LinkedList.
  3. ArrayList stores data in contiguous locations LinkedList store data using pointers and reference 
  4. LinkedList is better if we need to perform data manipulation , arrayList is better if we just want to send the data.
  • Explain Legacy collection in  java ?
All are synchronized
  1. Vector , Stack (LIFO ) :  dynamic array
  2. Dictionary (abstract) , Hashtable (concrete ), Properties ( string key and value , loaded to/from file)  :  key value pair ,null key not allowed 
  3. Enumeration : Iterate over legacy collection

  • How to make ArrayList thread safe.
  1. Use Collections.synchronizedList
  2. CopyOnWriteArrayList : can be modified during iteration but modified values will not be reflected .


  • How do HashMap handles different key with same hashcode ?
takes the hashcode of the key and check if it matches a with the hashcode of existing key . If the same hashcode exists then it compares both the keys using equals method . If both the keys are same it replaces the existing value with the new one . If both the keys does not match then it adds a new entry  in the same bucker .

  • What is BlockingQueue
Thread-safe , does not accept null value . FIFO . It is used to implement producer / consumer issues .
  1. put : add the element to the queue , if space is not available it waits for the space to be available.
  2. take : returns element from head of the queue , if no elements wait for the element to come.
  • What are the new features added in Java 7?
  1. Try with resources : the resources will be closed automatically (ARM), 
    • should implement AutoCloseable introduced in Java 7 .
    • to support ARM Suppressed Exceptions are introduced .
    • the exceptions originating at try block is propagated and the exceptions occurring in finally block is suppressed . 
    • addSuppressed and getSuppressed methods added in Throwable class
    • Closeable interface now extends AutoClosable interface .
  2. Multiple Exception in single catch separated by | . 
  3. Underscore in numeric literals
  4. Binary literals 0b,0B
  5. Switch case with string
  6.  Type interface for generic instance.using <> .
  7. Java.nio.file package : used to create, delete , copy , move etc. files and directories.
  8. @SafeVarargs : used by programmer to mark that no unsafe operations are performed in the constructor with var args .
  9. String constant pool is stored in heap instead of perm gen.

  • New features in Java 8
  1. Perm gen is removed.
  2. Functional interface
  3. Lambda support
  4. Interface default and static 
  5. For each in iterator
  6. Java stream API.
  7. Optional class : avoid null pointer
  • Explain interface default method :
  1. The implementing class does need not implement the default method.
  2. Sub interfaces can override or make it abstract .

  • Explain method reference
Static method 
Class name :: method name
Instance method
Object name:: method name


  • How does multiple inheritance issue for default method is handled .
It is mandatory for the implementing class to implement a default method in case of multiple inheritance issue .

  • What is optional class in Java 8
Pre defined action instead of throwing null pointer exception.


  • Explain functional interface

@FunctionalInterface annotation will add a compile time check for an interface to have only one abstract method. It will be used for lambda expressions.
  • Explain memory management in Java.
  1. Heap : stores object data.
  2. Permgen : stores class data ,method local initialization , string contact pool.
  3. Stack : store data required while returning from method
  • How to manage memory ?
  1. System.gc() or Runtime.gc() : garbage collector may be called .
  2. Runtime.freeMemory() : free memory 
  3. Runtime.totalMemory() : total memory available
  4. Runtime.maxMemory() : maximum memory that JVM is going to use
      • What is just in time compiler(JIT)
      converts byte code to native code to boost performance .
      • Explain Creational Design Patterns .
      1. Factory 
      2. Abstract Factory
      3. Builder : create complex object , method chaining .
      4. Singleton
      5. Prototype
      • Explain Structural Design Patter .
      1. Adapter
      2. Bridge
      3. Composite
      4. Decorator
      5. Facade
      6. Flywheel
      7. Proxy
      • Explain Behavioral Design Patter .
      1. Chain of Responsibility
      2. Command
      3. Interpretor : how to include language  elements
      4. Iterator
      5. Mediator : simplify communication between objects
      6. Observer : multiple objects notification
      7. State : modify the behavior on state change
      8. Template : abstract definition of algorithm
      9. Visitor : add polymorphic functions to class noninvasively .

      • How can we make singleton class thread safe.
      Null check for instance and creation of new object should be done inside a synchronized block.
      • What is executor service?
      It provides a pool of threads and API to assign task for it.Simplifies task execution in async mode.

      • What is Thread.yeald?
      Thread Scheduler checks if any other thread available with same or higher priority and transfer the processor to it .


      • Explain serialization

      1. Serializable interface should be implemented .
      2. Serializable is a marker interface for identification .
      3. sub class must be serializable ,  super class need not be serializable .
      4. Transient and static attributes are not serialized.
      5. readresolve method can be implemented and same instance can be returned, while deserialization of singleton class.
      6. Write replace is called before write object .

      • Explain serialVersionUID .
      1.  if it not present java compiler adds it .
      2.  it is static final and long . 
      3. It is used to check the sender and receiver are compatible if there is mismatch in the serialVersionUID InvalidClassException is thrown .
      4. If there is no serialVersionUID and we have serialized an object  , we added some field and now if we want to deserialize it we get InvalidClassException .


      • Explain Externalizable interface 
      used for custom serialization 

      1. readExternal
      2. writeExternal


      • Explain classloaders 
      they load classes during runtime dynamically .

      1. Bootstrap : parent of all , first to be loaded
      2. extension : load all classes from .jar from  java.ext.dirs
      3. system : loads the classes at java.class.path or classes specified at -classpath .

      Sunday, March 17, 2019

      Spring Interview Question

      Most Common Spring Interview Questions : This blog is just for a revision .


      • What is dependency injection ?
      Spring IoC container takes care of object creation and wiring them together.
      1. Constructor constructor-arg : for mandatory dependencies
      2. Setter ref : for optional dependencies
      3. using @Autowired
      • Types of IoC container?
      1. BeanFactory
      2. ApplicationContext
      • What are the advantages of ApplicationContext?
      1. Internationalization
      2. Annotation support
      3. Load all beans on start 
      4. lazy-init for lazy loading
      5. No need to register AutowiredBeanPostProcessor
      6. Automatic BeanPostProcessor , BeanFactoryPostProcessor registration
      7. Easy MessageSource access (for i18n)
      8. ApplicationEvent publication
      • Advantages of spring IoC ?
      1. Less code
      2. Easy testing
      3. Loose coupling
      4. Lazy loading
      • What is spring bean ?
      java class created by spring IoC container .
      • Explain Spring bean life cycle.
      1. Check the configuration
      2. Initialization
      3. Dependency Injection
      4. set bean name
      5. set bean class loader
      6. set bean factory
      7. set resource loader
      8. set application event publisher
      9. set message source 
      10. set Application Context
      11. set Servlet context
      12. postProcessBeforeInitialization
      13. afterPropertiesSet
      14. init method
      15. postProcessAfterInitialization
      16. destroy
      17. destroy
      • Explain scope of bean .
      1. singleton : default , one instance in the container 
      2. prototype : new instance every time the getBean is called
      3. request : one bean for life cycle of http request 
      4. session : one bean for life cycle of http session
      5. global session : one bean for life cycle of ServletContext
      • What is BeanPostProcessor ?
      implementation can define a callback method .
      1. postProcessBeforeInitialization  before init method
      2. postProcessAfterInitialization after init method
      • How to create ApplicationContext ?
      1. XML based :ClassPathXmlApplicationContext("xml file")
      2. Annotation based : in web-servlet.xml use  <context:component-scan base-package= > .
      3. Java based :  @Configuration ,  @Bean , @Scope, @Import , @ComponentScan
      • Explain  JSR 250  annotations used in spring .
      1. @PostConstruct : alternative to init 
      2. @PreDestroy : alternative to destroy
      3. @Resource(name ="")   : similar to @Autowired @Qualifier("") 
      • Explain other annotations in spring to be used with annotation based configuration
      1. @Required:applied on setter , the value should be provided in xml 
      2. @Component parent of annotations
        • @Controller , 
        • @Repository , 
        • @Service 
      •  Explain Autowiring .
      Enables us to inject dependency implicitly, using autowire in xml
      1. no : explicit bean references 
      2. byName : by the bean name in xml file.
      3. byType : matches the type of the bean 
      4. contructor : check the type of the parameter in constructor 
      • Explain inner bean 
      A bean used as property of another bean . A <bean> inside <property> .
      • What are the new features in Spring 4 .
      1. Added path to RequestMapping
      2. MVC test framework
      3. @RestController and AsyncRestTemplate is used.
      4. instread of response it returns ListenableFuture 
      5. uses java 8 , minimum requirement is Java 6.
      6. define external bean configuration using a Groovy
      7. Added @Description
      8. @Lazy can be used in bean injection and definition .
      9. @Autowired @Value can be used as meta annotations
      10. Introduced ordering for autowired , using @Order and Ordered interface .
      11. @Bean in @Configuration Class
      12. Conditional filtering of beans added for @Conditional .
      13. Generic type as qualifier for injecting bean
      14. create custom annotation to expose attribute of the source annotation .
      • New features added in Spring 5.
      1. bean scopes : singleton, prototype , request , session , application , websocket (one bean for lifecycle of Websocket )


      • Explain the components of Spring MVC.
      1. Dispatcher Servlet
      2. Handler Mapping
      3. Controller
      4. Model And View
      5. View Resolver
      6. View
      • Explain Dispatcher Servlet
      Front Controller for all incoming Request.
      entry added in web.xml for dispatcher servlet
        • org.springframework.web.servlet.DispatcherServlet
        • loadOnStartUp = 1
      Create {servlet-name}-servlet.xml,specify

        • context:component-scan
        • mvc:annotation-driven



      • What is handler mapping

      Dispatcher servlet checks with handler mapping and  redirects to the appropriate controller .


      • What is view resolver ?
      It determines the view to which the request has to be transferred .

      1. InternalResourceViewResolver : based on URL , suffix and prifix
      2. XmlViewResolver : view definition in  a dedicated XML .
      3. ResourceBundleViewResolver : view definition in a property file .




        • What is ServletContext ?
        One per application , created once the web application is deployed .
        To access in spring context , the controller must implement ServletContextAware   ,add either of the following code  
        1. 
        @Autowired
        ServletContext context; 

        2.
        private ServletContext context;

        public void setServletContext(ServletContext servletContext) {
            this.context = servletContext;
        }

        Methods :

        1. getInitParameter () : returns value set in <context-param> <param-name>
        • What is servletConfig?
        One per servlet

        1. getInitParameter(String name): returns value set in <init-param><name>  
        2. getInitParameterNames(): returns all <init-param>
        3. getServletContext(): returns ServletContext
        4. getServletName(): returns value set in <servlet><servlet-name>


        • What is servlet context listener ?

        gets notified when servlet context is initialized or destroyed .
        • Explain  Spring MVC annotations?
        1. @Controller : class is a web request handler 
        2. @Component : auto-detection when using annotation-based 
        3.  @RestController = @Controller + @ResponseBody
        4. @RequestMapping method: get/put value : URL
        5. @PathVariable input in request URL.
        6. @RequestParam input in url with ?id=
        7. @Transactional : can be applied to class or method.
        8. @EnableWebMvc enable spring MVC through java configuration.

        • What is WebMvcConfigurer .

        To customise web MVC configuration.
        Like add view controller
        View resolver in java code .


        • What is WebApplicationInitializer

        used to configure servlet context programmatically , used as an alternative to configuration in web.xml


        • Explain file upload in spring 
        1. use CommonsMultipartResolver add dependency commons-fileupload
        2. add bean configuration in servlet-config.xml file 
          • "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        3. input type = file in html
        4. @RequestParam MultipartFile
        • What is a profile

        If we want enable a bean only during development and not in production we can assign the profile to the bean , using @Profile("dev")

        • How to declare a profile ?
        1. Set the servlet context init Param using WebApplicationInitializer
        2. Set context Param in web.xml
        3. Set the JVM system parameter
        4. Set the environment variable
        5. Set in maven profile
        6.  Configurable environment set active profile
        • Explain spring events 
        1. event class should extend ApplicationEvent
        2. publish event can be done using applicationEventPublisher.publishEvent(customSpringEvent);
        3. listener has to implement ApplicationListener<MyEvent>
        4. listener need to override onApplicationEvent(MyEvent myEvent)
        • What are the events related to ApplicationContext
        1. ContextRefreshedEvent
        2. ContextStartedEvent
        3. ContextStoppedEvent
        4. ContextClosedEvent
        • What is Join Point ?
        An event occurred during the execution of a program.
        1. method called 
        2. state changed
        3. exception occurred 
        • What is an Point Cut ?
        an expression
        • What is an advice ?
        Action taken (method ).
        1. before
        2. after
        3. around : decides whether the method gets executed or not
        4. afterReturning :executed only if method executed successfully .
        5. afterThrowing : executed only if exception is occurred during method execution .
        • What is aspect ?
        class that implements cross cutting concerns .
        1. logging
        2. security
        3. transaction management
        4. exception handling
        5. performance testing
        • What is weaving?
        Linking aspect with other objects/application types to create adviced object.
        • What is proxy?
        Object created after applying advice to target object.


        • What are the features of spring boot?
        1. Auto configuration : configure beans based on the jar available at classpath  and beans used in the project . Annotations used : @ConditionalOnClass, @ConditionalOnMissingBean .
        2. Starters project
        3. Cli using groovy
        4. Actuator
        5. Initializer

        • Explain Spring Boot Annotations
        1. @SpringBootApplication 
        2. @EnableAutoConfiguration
        • What is Spring Boot Initilizr ?
        It is used to generate a new project .


        • What is Spring Boot Actuator
        adds production grade services to the application

        1. info
        2. health : up
        3. trace
        4. httptrace

        • How do you create Logger in Spring boot .
        org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MyClass.class);
        configure logger level , file path , pattern console profile in application.properties
        create logback.xml



        ec2-user@ec2 Permission denied