Autowiring vs new Object Keyword

Autowiring new Object()
decouples object creation and life-cycle from object binding and usage Using new Keyword creates new Object everytime.The object graph grows over a period of time.Consider UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection – it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code
Autowiring offers object at different scopes – Singleton, request and prototype All objects are JVM Scope

How Autowiring works
The autowiring happens when the application starts up, during the time of deployment.When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically.

Lets see a example where the dependencies are resolved by XML and annotation
ApplicationContext.xml

<beans ...>
    <bean id="userService" class="com.foo.UserServiceImpl"/>
    <bean id="fooController" class="com.foo.FooController"/>
</beans>

When it sees @Autowired, Spring will look for a class that matches the property in the applicationContext, and inject it automatically. If you have more than 1 UserService bean, then you’ll have to qualify which one it should use.

FooController.java

public class FooController 
{
    // You could also annotate the setUserService method instead of this
    @Autowired
    private UserService userService;

    // rest of class goes here
}

Things to Note while Autowiring

  1. Marks a constructor, field, setter method or config method as to be autowired by Spring’s dependency injection facilities.
  2. Only one constructor (at max) of any given bean class may carry this annotation, indicating the constructor to autowire when used as a Spring bean. Such a constructor does not have to be public.
  3. Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
  4. •In the case of multiple argument methods, the ‘required’ parameter is applicable for all arguments.

Annotation or XML
For instance, if using Spring, it is entirely intuitive to use XML for the dependency injection portion of your application. This gets the code’s dependencies away from the code which will be using it, by contrast, using some sort of annotation in the code that needs the dependencies makes the code aware of this automatic configuration.

However, instead of using XML for transactional management, marking a method as transactional with an annotation makes perfect sense, since this is information a programmer would probably wish to know. But that an interface is going to be injected as a SubtypeY instead of a SubtypeX should not be included in the class, because if now you wish to inject SubtypeX, you have to change your code, whereas you had an interface contract before anyways, so with XML, you would just need to change the XML mappings and it is fairly quick and painless to do so.

I haven’t used JPA annotations, so I don’t know how good they are, but I would argue that leaving the mapping of beans to the database in XML is also good, as the object shouldn’t care where its information came from.If an annotation provides functionality and acts as a comment in and of itself, and doesn’t tie the code down to some specific process in order to function normally without this annotation, then go for annotations. For example, a transactional method marked as being transactional does not kill its operating logic, and serves as a good code-level comment as well. Otherwise, this information is probably best expressed as XML, because although it will eventually affect how the code operates, it won’t change the main functionality of the code, and hence doesn’t belong in the source files.

How auto wiring works in Spring

  1. All Spring beans are managed – they “live” inside a container, called “application context”.the application context is bootstrapped and all beans – autowired. In web applications this can be a startup listener.
  2. All application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver
  3. the context instantiates the objects, not you. I.e. – you never make new UserServiceImpl() – the container finds each injection point and sets an instance there.
  4. applicationContext.xml you should enable the so that classes are scanned for the @Controller, @Service, etc. annotations.
  5. Apart from the @Autowired annotation, Spring can use XML-configurable autowiring. In that case all fields that have a name or type that matches with an existing bean automatically get a bean injected. In fact, that was the initial idea of autowiring – to have fields injected with dependencies without any configuration. Other annotations like @Inject, @Resource can also be used

Problem
When using getResultList() to retrieve the Rows of the DB table there may be times where you would end up getting the same rows multiple times.

Why this Happens
Let’s have a table tblGroup the one below

ParentGrp GrpName
Finance Accounts
Finance Sales
  1. You have 2 records in database.Both the records has Finance as value in parentGrp column
  2. Now when you run a select query to select parentGrp = ‘Finance’ you will get 2 records
  3. Lets query them WHERE parentGrp = ‘Finance’
  4. SQL Query returns 2 rows
  5. Hibernate loads first one, and puts into session, with parentGrp as a key.Now this will happen if you have specified it as @ID in entity class or you havent specified it while joining two tables in entity class.The object is placed into the result list.
  6. Hibernate loads second one, notices that an object with the same @Id is already in the session, and just places the reference into the result List. Row data are ignored.
  7. Now we have two copies of the same record

Solution:
We can solve this by introducing a primary key column something like tblGroup_pk_id.Now this helps to uniquely identify the records in the table so it won’t get overridden when the next rows retrieved.

Now the GrpId should be entitled with @ID annotation in the entity class.

GrpId ParentGrp GrpName
101 Finance Accounts
102 Finance Sales
createQuery() createSQLQuery() createCriteria()
Creates Query Object Creates Query Object Creates Criteria Object
Uses HQL Syntax Uses DB Specific Syntax Uses Entity Class
The Columns of the rows retrieved would be name of the POJO Model Class The Columns of the rows retrieved would be name of Native DB fields Create sql query using Criteria object for setting the query parameters
CRUD operation could be done CRUD operation could be done Only Read Operation is allowed
Supports Interoperability between different DB’s Does not support Interoperability since the query format should be changed when the DB is changed Supports Interoperability between different DB’s
Does not work without Model Class Bean with columns of Table alone is Enough.No need for Entity class generation Does not work without Model Class
No need for mapping between Entity class object and Table Columns The Bean Objects should be mapped with table Columns No need for mapping

createQuery – session.createQuery()

------------------------------------------------------
**DB_TBL_Col(tblEmployee)**| **POJO(Employee)**
EMP_ID                     | employeeID
------------------------------------------------------
Query query = session.createQuery("from Employee E where E.employeeID = 'A%'");
List<Person> persons = query.list();

parent-pom.xml

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8</version>
    </dependency>
 </dependencies>
</dependencyManagement>

child-pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
 </dependencies>

Two Main Differeneces

  1. Dependency Management allows to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. This is especially useful when you have a set of projects (i.e. more than one) that inherits a common parent.Another extremely important use case of dependencyManagement is the control of versions of artifacts used in transitive dependencies.You still need to define them in the child POM to show that you are using them. They are not actually included in the child projects just because they are in in the parent POM. Enclosing dependencies in centralizes management of the version, scope, and exclusions for each dependency, if and when you decide to use it.
  2. Artifacts specified in the section <dependencies> will ALWAYS be included as a dependency of the child module(s).Artifacts specified in the section will only be included in the child module if they were also specified in the section of the child module itself. Why is it good you ask? because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.

To sum up the above points in simple words in the parent-pom.xml if you are adding things inside tag then it would be available to the child-pom.xml. If you are adding the same thing within tag then you should manually add them to the child-pom.xml.In the child-pom.xml if the version is not specified it will take the parent-pom.xml version of the dependency as default else you can override them by specifying one in child-pom.xml

References Read It

BuildDeploy.bat

 cscript /nologo c:\Utils\stopjboss.vbs

 set JBOSS_DEPLOYMENT=c:\jboss\standalone\deployments
 set DEVELOPMENT_HOME=c:\projectName
 set BRANCH=BranchName\ReleaseNo
 
 del /q %JBOSS_DEPLOYMENT%\*.*
 cd %DEVELOPMENT_HOME%\%BRANCH%
 
 call mvn clean
 call mvn install -o
 
 IF EXISTS  %DEVELOPMENT_HOME%\%BRANCH%\SpringMVC.war (
  goto :startServer
 ) else (
  echo Build Failed
 )

 exit /b

:startServer
 copy %DEVELOPMENT_HOME%\%BRANCH%\SpringMVC.war %JBOSS_DEPLOYMENT%
 cscript /nologo c:\Utils\startjboss.vbs
goto :eof

startjboss.vbs

 Set WshShell = WScript.CreateObject("WScript.Shell")
 activateServer("Server")
 WshShell.SendKeys "%{d}"

 Function activateServer(windowName)
   WshShell.SendKeys "^{3}"
   WScript.Sleep 500
   WshShell.SendKeys windowName
   WScript.Sleep 500
   WshShell.SendKeys "{ENTER}"
 End Function

stopjboss.vbs

 Set WshShell = WScript.CreateObject("WScript.Shell")
 activateServer("Server")
 WshShell.SendKeys "%{s}"
 WScript.Sleep 5000

How it Works

  • We are using a VBScript to Start and Stop server by Sending Key Strokes to Eclipse(Shortcut Keys)
  • The mvn clean and mvn install is done in 2 different steps to make sure that clean of the war files happen before the new file is created since executing clean and install in single shot happened to give inconsistent results
  • Once the build is done we are checking whether the war file is created or we are assuming the build failed and we are not starting the server
  • The builddeploy.bat should be configured in External Tools Configuration
  • Workdirectory is the one which has pom.xml of the project
  • Assign a shortcut key to Run Last Run Build Configuration

How to arrange Two excel sheets side by Side

Steps

  • Click on View tab, Click on New Window
  • Click on Arrange All, Select Vertical

Now to compare 2 Rows in 2 Excel Sheets

  • Select the Rows in the Sheet which needs to be compared
  • Click on Conditional Formatting Option
  • =ISNA(MATCH(A2,Sheet2!A2,FALSE))

If you want the formatting to be applied only for one Column select that column and apply conditional formatting

Instead of

 =$A$2:$B$7

it should be

 =$A$2:$A$7

in Conditional Rules Formatting Manager

Download Excel

How to highlight rows which have different row value of one Column

null

The Steps are as Below
Below is the way to highlight the rows based on a change in value in the single column.The Column considered is SNo

Steps

  • Select the whole DataSet LookUpArray on which the conditional formatting to be applied
  • Click on Conditional Formatting
  • Click on new Rule
  • Use a formula to determine which cells to format
  • Note : The formula used is relative formula =ISNA(MATCH($D2,$A$2:$A$7,FALSE))
  • Use the format option to apply the Conditional format on the cells
  • The same could be seen in Conditional Formatting->Manage Rules for future rule edits

In the below image Rows 4 and 7 are highlighted because of mismatch in SNo and 5 is highlighted because of mismatch in fruit name

Checking for Identical rows in two tables with more than one column

 =ISNA(MATCH($D2,$A$2:$A$7,FALSE)&MATCH($E2,$B$2:$B$7,FALSE) )

Steps

  • First we are checking if the rows in D2 is same as on in A2 to A7
  • Second we are checking if the rows in E2 is same as on in B2 to B7