Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Spring

The document discusses the differences between Inversion of Control (IOC) and Dependency Injection (DI) in Spring. It provides examples of Spring annotations such as @Component, @Controller, @Service, @Repository, @Autowired, @Transactional and @RequestMapping that are used to configure Spring components, services and controllers. The document also explains how to define and inject Spring beans using @Configuration and @Bean annotations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Spring

The document discusses the differences between Inversion of Control (IOC) and Dependency Injection (DI) in Spring. It provides examples of Spring annotations such as @Component, @Controller, @Service, @Repository, @Autowired, @Transactional and @RequestMapping that are used to configure Spring components, services and controllers. The document also explains how to define and inject Spring beans using @Configuration and @Bean annotations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Difference between IOC & DI

IOC(Inversion Of Controller) : Giving control to the container to get instance of


object is called Inversion of Control., means instead of you are creating object
using new operator, let the container do that for you.
DI(Dependency Injection): Passing the required parameters(properties) from
XML to an object(in POJO CLASS) is called Dependency injection.

Sr.No. Annotation & Description

1 @Required

The @Required annotation applies to bean property setter methods.

2 @Autowired

The @Autowired annotation can apply to bean property setter


methods, non-setter methods, constructor and properties.

3 @Qualifier

The @Qualifier annotation along with @Autowired can be used to


remove the confusion by specifiying which exact bean will be wired.

@Configuration & @Bean Annotations

Annotating a class with the @Configuration indicates that the class can be used


by the Spring IoC container as a source of bean definitions. The @Bean annotation
tells Spring that a method annotated with @Bean will return an object that should
be registered as a bean in the Spring application context.
package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

The above code will be equivalent to the following XML configuration −

<beans>
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" />
</beans>

Here, the method name is annotated with @Bean works as bean ID and it creates
and returns the actual bean. Your configuration class can have a declaration for
more than one @Bean. Once your configuration classes are defined, you can load
and provide them to Spring container using AnnotationConfigApplicationContext as
follows −

public static void main(String[] args) {


ApplicationContext ctx = new
AnnotationConfigApplicationContext(HelloWorldConfig.class);

HelloWorld helloWorld = ctx.getBean(HelloWorld.class);


helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}

The @Import Annotation


The @Import annotation allows for loading @Bean definitions from another
configuration class. Consider a ConfigA class as follows −
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}

You can import above Bean declaration in another Bean Declaration as follows −

@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B a() {
return new A();
}
}

Now, rather than needing to specify both ConfigA.class and ConfigB.class when
instantiating the context, only ConfigB needs to be supplied as follows −

public static void main(String[] args) {


ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

// now both beans A and B will be available...


A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}

Injecting Bean Dependencies


When @Beans have dependencies on one another, expressing that the dependency
is as simple as having one bean method calling another as follows −
package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}

Here, the foo bean receives a reference to bar via the constructor injection. Now
let us look at another working example.

Specifying Bean Scope


The default scope is singleton, but you can override this with the @Scope
annotation as follows −

@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public Foo foo() {
return new Foo();
}
}
@Service
Annotate all your service classes with @Service. All your business logic should be in
Service classes.

@Service
public class CompanyServiceImpl implements CompanyService {
...
}

@Repository
Annotate all your DAO classes with @Repository. All your database access logic
should be in DAO classes.

@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}

@Component
Annotate your other components (for example REST resource classes) with
@Component.

@Component
public class ContactResource {
...
}
@Component is a generic stereotype for any Spring-managed component.
@Repository, @Service, and @Controller are specializations of @Component for
more specific use cases, for example, in the persistence, service, and presentation
layers, respectively. 
@Autowired
Let Spring auto-wire other beans into your classes using @Autowired annotation. 

@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

...
}
Spring beans can be wired by name or by type.

 @Autowire by default is a type driven injection. @Qualifier spring


annotation can be used to further fine-tune autowiring.
 @Resource (javax.annotation.Resource) annotation can be used for
wiring by name.

Beans that are themselves defined as a collection or map type cannot be


injected through @Autowired, because type matching is not properly
applicable to them. Use @Resource for such beans, referring to the
specific collection or map bean by unique name.

@Transactional
Configure your transactions with @Transactional spring annotation.

@Service
public class CompanyServiceImpl implements CompanyService {

@Autowired
private CompanyDAO companyDAO;

@Transactional
public Company findByName(String name) {

Company company = companyDAO.findByName(name);


return company;
}
...
@Scope
As with Spring-managed components in general, the default and most common
scope for autodetected components is singleton. To change this default behavior,
use @Scope spring annotation.

@Component
@Scope("request")
public class ContactResource {
...
}
Similarly, you can annotate your component with @Scope("prototype") for beans
with prototype scopes.

Spring MVC Annotations

@Controller
Annotate your controller classes with @Controller.

@Controller
public class CompanyController {
...
}

@RequestMapping
You use the @RequestMapping spring annotation to map URLs onto an entire class
or a particular handler method. Typically the class-level annotation maps a specific
request path (or path pattern) onto a form controller, with additional method-level
annotations narrowing the primary mapping.

@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;
...
}

@PathVariable
You can use the @PathVariable spring annotation on a method argument to bind it
to the value of a URI template variable. In our example below, a request path of
/company/techferry will bind companyName variable with 'techferry' value.

@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;

@RequestMapping("{companyName}")
public String getCompany(Map<String, Object> map,
@PathVariable String companyName) {
Company company = companyService.findByName(companyName);
map.put("company", company);
return "company";
}
...
}

@RequestParam
You can bind request parameters to method variables using spring annotation
@RequestParam.

@Controller
@RequestMapping("/company")
public class CompanyController {

@Autowired
private CompanyService companyService;

@RequestMapping("/companyList")
public String listCompanies(Map<String, Object> map,
@RequestParam int pageNum) {
map.put("pageNum", pageNum);
map.put("companyList", companyService.listCompanies(pageNum));
return "companyList";
}
...
}
Similarly, you can use spring annotation @RequestHeader to bind request headers.

@ModelAttribute
An @ModelAttribute on a method argument indicates the argument should be
retrieved from the model. If not present in the model, the argument should be
instantiated first and then added to the model. Once present in the model, the
argument's fields should be populated from all request parameters that have
matching names. This is known as data binding in Spring MVC,

@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyService companyService;

@RequestMapping("/add")
public String saveNewCompany(@ModelAttribute Company company) {
companyService.add(company);
return "redirect:" + company.getName();
}
...
}

@SessionAttributes
@SessionAttributes spring annotation declares session attributes. This will typically
list the names of model attributes which should be transparently stored in the
session, serving as form-backing beans between subsequent requests.

@Controller
@RequestMapping("/company")
@SessionAttributes("company")
public class CompanyController {

@Autowired
private CompanyService companyService;
...
}
@SessionAttribute works as follows:

 @SessionAttribute is initialized when you put the corresponding attribute into


model (either explicitly or using @ModelAttribute-annotated method).
 @SessionAttribute is updated by the data from HTTP parameters when
controller method with the corresponding model attribute in its signature is
invoked.
 @SessionAttributes are cleared when you call setComplete() on
SessionStatus object passed into controller method as an argument.

The following listing illustrate these concepts. It is also an example for pre-
populating Model objects.
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

@ModelAttribute("types")

public Collection<PetType> populatePetTypes() {


return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}

Spring Security Annotations

@PreAuthorize
Using Spring Security @PreAuthorize annotation, you can authorize or deny a
functionality. In our example below, only a user with Admin role has the access to
delete a contact.

@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}

 Spring MVC 3 Validation

Beginning with Spring 3, Spring MVC has the ability to automatically


validate @Controller inputs. In previous versions it was up to the developer to
manually invoke validation logic.

Triggering @Controller Input Validation

To trigger validation of a @Controller input, simply annotate the input argument


as @Valid:

@Controller

public class MyController {

@RequestMapping("/foo", method=RequestMethod.POST)
public void processFoo(@Valid Foo foo) { /* ... */ }

Spring MVC will validate a @Valid object after binding so-long as an appropriate
Validator has been configured.

Writing messages.propreties file

We localize validation error messages for the email field, so put the following
key=value pairs in messages.properties file:

1 NotEmpty.userForm.email=Please enter your e-mail.

2 Email.userForm.email=Your e-mail is incorrect.

Configuring Spring framework in web.xml

Enable Spring dispatcher servlet in the web deployment descriptor file:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

        id="WebApp_ID" version="3.0">

    <display-name>SpringMvcFormValidationExample</display-name>

    <servlet>

        <servlet-name>SpringController</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc.xml</param-value>

        </init-param>

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>SpringController</servlet-name>

        <url-pattern>/</url-pattern>

    </servlet-mapping>

</web-app>

Spring MVC : How to perform validation ?

With Spring MVC, there are 3 different ways to perform validation : using
annotation, manually, or a mix of both.

Let's have a User :

public class User {

private String name;

...

Method 1 : If you have Spring 3.x+ and simple validation to do,
use javax.validation.constraintsannotations.

public class User {

@NotNull
private String name;

...

Then in your controller you would have something like :

@RequestMapping(value="/user", method=RequestMethod.POST)

public createUser(Model model, @Valid @ModelAttribute("user") User user,


BindingResult result){

if (result.hasErrors()){

// do something

else {

// do something else

Notice the @Valid : if the user happens to have a null name, result.hasErrors() will
be true.

Method 2 : If you have complex validation (like big business validation logic,
conditional validation across multiple fields, etc.), or for some reason you cannot
use method 1, use manual validation. It is a good practice to separate the
controller’s code from the validation logic. Don't create your validation class(es)
from scratch, Spring provides a
handy org.springframework.validation.Validatorinterface (since Spring 2).

So let's say you have

public class User {

private String name;


private Integer birthYear;

private User responsibleUser;

...

and you want to do some "complex" validation like : if the user's age is under 18,
responsibleUser must not be null and responsibleUser's age must be over 21.

You will do something like this

public class UserValidator implements Validator {

@Override

public boolean supports(Class clazz) {

return User.class.equals(clazz);

@Override

public void validate(Object target, Errors errors) {

User user = (User) target;

if(user.getName() == null) {

errors.rejectValue("name", "your_error_code");

// do "complex" validation here


}

Then in your controller you would have :

@RequestMapping(value="/user", method=RequestMethod.POST)

public createUser(Model model, @ModelAttribute("user") User user,


BindingResult result){

UserValidator userValidator = new UserValidator();

userValidator.validate(user, result);

if (result.hasErrors()){

// do something

else {

// do something else

If there are validation errors, result.hasErrors() will be true.

Method 3 : Why not using a combination of both methods? Validate the simple
stuff, like the "name" attribute, with annotations (it is quick to do, concise and
more readable). Keep the heavy validations for validators (when it would take
hours to code custom complex validation annotations, or just when it is not possible
to use annotations). I did this on a former project, it worked like a charm, quick &
easy.
Bullet Points

 Container will contain beans as long as they are required by Application.


 Beans created outside Spring container can also be registered with
AC(Application Context).
 BeanFactory is root interface for accessing the bean container. Other
interfaces are also available for specific purpose.
 BeanFactory is a central registry of application components(Beans).
 These component(Beans) have lifecycle interfaces and methodswhich will
be invoked in some order before Bean can be handed over to application and
before Bean is getting destroyed.

Bean LifeCycle :

When bean is initialized it might require to perform some activity before it can
come into useable state(State in which application can use it) and when bean is
getting destroyed there might be some cleanup activity required for given bean.
These activities are known as bean Lifecycle.

Standard bean lifecycle interfaces & there standard order of execution are given
below..
1-   IoC container will look for the configuration metadata of given Bean.
2-   Once find, container will create the instance of Bean(Using reflection API).
3-   After instance creation dependency will be injected(DI).

If Bean Class implements any of the below highlighted interface then corresponding


method will be invoked in below order (Point 4 – 13).

 4-   setBeanName method of BeanNameAware Interface. It sets the name of the


bean in the bean factory that created this bean.
 5-   setBeanClassLoader method of BeanClassLoaderAwareInterface. Callback
that supplies the bean to a bean instance.
 6-   setBeanFactory  method of BeanFactoryAware Interface. Callback that
supplies the owning factory to a bean instance.

Below method execution will be applicable when running in an application context.


(Points 7 – 11)

 7-   setResourceLoader  method of ResourceLoaderAware Interface. It set the


ResourceLoader that this object runs in.
8-   setApplicationEventPublisher  method
of ApplicationEventPublisherAware Interface. Set the ApplicationEventPublisher
that this object runs in.
9-   setMessageSource method of MessageSourceAware Interface. Set the
MessageSource that this object runs in.
10-   setApplicationContext method of ApplicationContextAwareInterface. Set
the ApplicationContext that this object runs in.
11-   setServletContext method of ServletContextAware Interface. Set the
ServletContext that this object runs in.

12-   postProcessBeforeInitialization method of BeanPostProcessorInterface.


Apply this BeanPostProcessor to the given new bean instance before any bean
initialization callbacks.
13-   afterPropertiesSet method of InitializingBean Interface. Invoked by a
BeanFactory after it has set all bean properties supplied.

In case Bean class has custom init method defined(via init-method attribute)

14-   Custom init method will be invoked.


15-   postProcessAfterInitialization methods of BeanPostProcessors. Apply this
BeanPostProcessor to the given new bean instance after any bean initialization
callbacks

When Bean Factory is getting shut down following lifecycle methods will be
executed.

1-   DisposableBean’s destroy method. Invoked by a BeanFactory on destruction of


a singleton.
2-   Custome destroy method will be executed if there is any defined via destroy-
method attributes

Spring Bean Life Cycle – @PostConstruct, @PreDestroy

Below is a simple class that will be configured as spring bean and for post-init and
pre-destroy methods, we are using @PostConstruct and @PreDestroy annotations.

package com.journaldev.spring.service;

import javax.annotation.PostConstruct;

import javax.annotation.PreDestroy;
public class MyService {

@PostConstruct

public void init(){

System.out.println("MyService init method called");

public MyService(){

System.out.println("MyService no-args constructor called");

@PreDestroy

public void destory(){

System.out.println("MyService destroy method called");

Spring Bean Life Cycle – Configuration File

Let’s see how we will configure our beans in spring context file.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- Not initializing employee name variable-->

<bean name="employee" class="com.journaldev.spring.bean.Employee" />

<bean name="employeeService"
class="com.journaldev.spring.service.EmployeeService">

<property name="employee" ref="employee"></property>

</bean>

<bean name="myEmployeeService"
class="com.journaldev.spring.service.MyEmployeeService"

init-method="init" destroy-method="destroy">

<property name="employee" ref="employee"></property>

</bean>

<!-- initializing CommonAnnotationBeanPostProcessor is same as


context:annotation-config -->

<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProce
ssor" />

<bean name="myService" class="com.journaldev.spring.service.MyService" />

</beans>

BeanFactory – BeanFactory implementation example

A  BeanFactory  is an implementation of the factory pattern that applies Inversion of


Control to separate the application’s configuration and dependencies from the
actual application code.
The most commonly used  BeanFactory  implementation is
the  XmlBeanFactory  class.

XMLBeanFactory

The most useful one is  org.springframework.beans.factory.xml.XmlBeanFactory ,


which loads its beans based on the definitions contained in an XML file. This
container reads the configuration metadata from an XML file and uses it to create a
fully configured system or application.

Spring configuration file

Spring configuration file is an XML file. This file contains the classes information and
describes how these classes are configured and introduced to each other.

What is Spring IoC container?

The Spring IoC is responsible for creating the objects, managing them (with
dependency injection (DI)), wiring them together, configuring them, as also
managing their complete lifecycle.

What are the benefits of IOC?

IOC or dependency injection minimizes the amount of code in an application. It


makes easy to test applications, since no singletons or JNDI lookup mechanisms are
required in unit tests. Loose coupling is promoted with minimal effort and least
intrusive mechanism. IOC containers support eager instantiation and lazy loading of
services.

What are the common implementations of the Application Context?

The FileSystemXmlApplicationContext container loads the definitions of the


beans from an XML file. The full path of the XML bean configuration file must be
provided to the constructor.
The ClassPathXmlApplicationContext container also loads the definitions of the
beans from an XML file. Here, you need to set  CLASSPATH  properly because this
container will look bean configuration XML file in  CLASSPATH .
The WebXmlApplicationContext: container loads the XML file with definitions of
all beans from within a web application.

Dependency Injection
What are the different types of IoC (dependency injection)?

 Constructor-based dependency injection: Constructor-based DI is


accomplished when the container invokes a class constructor with a number of
arguments, each representing a dependency on other class.
 Setter-based dependency injection: Setter-based DI is accomplished by the
container calling setter methods on your beans after invoking a no-argument
constructor or no-argument static factory method to instantiate your bean.

Which DI would you suggest Constructor-based or setter-based DI?

You can use both Constructor-based and Setter-based Dependency Injection. The
best solution is using constructor arguments for mandatory dependencies and
setters for optional dependencies.
 

Spring Beans

What are Spring beans?

The Spring Beans are Java Objects that form the backbone of a Spring application.
They are instantiated, assembled, and managed by the Spring IoC container. These
beans are created with the configuration metadata that is supplied to the container,
for example, in the form of XML  <bean/>  definitions.
Beans defined in spring framework are singleton beans. There is an attribute in
bean tag named  "singleton"  if specified true then bean becomes singleton and if
set to false then the bean becomes a prototype bean. By default it is set to true.
So, all the beans in spring framework are by default singleton beans.

What does a Spring Bean definition contain?

A Spring Bean definition contains all configuration metadata which is needed for the
container to know how to create a bean, its lifecycle details and its dependencies.

How do you provide configuration metadata to the Spring Container?

There are three important methods to provide configuration metadata to the Spring
Container:
 XML based configuration file.
 Annotation-based configuration
How do you define the scope of a bean?

When defining a  <bean>  in Spring, we can also declare a scope for the bean. It
can be defined through the  scope  attribute in the bean definition. For example,
when Spring has to produce a new bean instance each time one is needed, the
bean’s scope  attribute to be  prototype . On the other hand, when the same
instance of a bean must be returned by Spring every time it is needed, the the
bean  scope  attribute must be set to  singleton .

Explain the bean scopes supported by Spring

There are five scoped provided by the Spring Framework supports following five
scopes:
 In singleton scope, Spring scopes the bean definition to a single instance per
Spring IoC container.
 In prototype scope, a single bean definition has any number of object
instances.
 In request scope, a bean is defined to an HTTP request. This scope is valid only
in a web-aware Spring ApplicationContext.
 In session scope, a bean definition is scoped to an HTTP session. This scope is
also valid only in a web-aware Spring ApplicationContext.
 In global-session scope, a bean definition is scoped to a global HTTP session.
This is also a case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is  Singleton .

Are Singleton beans thread safe in Spring Framework?

No, singleton beans are not thread-safe in Spring framework.

Are there limitations with autowiring?

Limitations of autowiring are:


 Overriding: You can still specify dependencies using  <constructor-
arg>  and  <property>  settings which will always override autowiring.
 Primitive data types: You cannot autowire simple properties such as
primitives, Strings, and Classes.
 Confusing nature: Autowiring is less exact than explicit wiring, so if possible
prefer using explicit wiring.
Can you inject null and empty string values in Spring?

Yes, you can.


 

When to use Dependency Injections?

There are different scenarios where you Dependency Injections are useful.

 You need to inject configuration data into one or more component.


 You need to inject the same dependency into multiple components.
 You need to inject different implementation of the same dependency.
 You need to inject the same implementation in different configuration.
 You need some of the services provided by container.

When you should not use Dependency Injection?

There were scenarios where you don’t need dependency injections e.g.

 You will never need a different implementation.


 You will never need different configurations.

How you will decide when to use prototype scope and when singleton
scope bean?

You should use the prototype scope for all beans that are stateful and the singleton
scope should be used for stateless beans.

v.v.imp

How to Call Stored procedure in Spring Framework?

To call a Stored procedure in Spring framework you need to create Class which
should extends StoredProcedure class. Take the example of getting Employee
Details by Employee Id. package com.mytest.spring.storeproc

import java.sql.ResultSet;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeInfo extends StoredProcedure {

                      private static final String EMP_ID = "EMP_ID"; 


                      private static final String EMP_NAME = "EMP_NAME";
                      private static final String JOIN_DATE = "JOIN_DATE";
                      public SnapshotSearchStoredProcedure(DataSource dataSource,
String procedureName) 
                      {
                            super(dataSource, procedureName); 
                           declareParameter(new SqlParameter(EMP_ID, Types.NUMERIC));
                           declareParameter(new SqlOutParameter(EMP_NAME,
Types.VARCHAR));
                           declareParameter(new SqlOutParameter(JOIN_DATE,
Types.VARCHAR));
                           compile ();
                      }

                       public Map execute(Integer empId) 


                       {
                                  Map<String, Object> inputs = new HashMap<String,
Object>();
                                  inputs.put(P_CLD_IDR, empId);
                                  Map<String, Object> result = execute (inputs);
                                  return result;
                       }
}

You just need to call the execute method from the DAO layer.

Differentiate between BeanFactory and ApplicationContext in spring.

- With ApplicationContext more than one config files are possible while only one
config file or .xml file is possible with BeanFactory. 
- ApplicationContext publishes events to beans that are registered as listeners while
BeanFactory doesn't support this
- ApplicationContext support internationalization messages, application life-cycle
events, validation and many enterprise services like JNDI access, EJB integration,
remoting etc. while BeanFactory doesn't support any of these.

How do beans become 'singleton' or prototype?

- There exists an attribute in bean tag, called 'singleton’. 


- If it is marked 'true', the bean becomes singleton. 
- If it is marked 'false', the bean becomes prototype.

Explain Bean lifecycle in Spring framework?


Following is sequence of a bean lifecycle in Spring:

 Instantiate - First the spring container finds the bean's definition from the
XML file and instantiates the bean..
 Populate properties - Using the dependency injection, spring populates all
of the properties as specified in the bean definition..

 Set Bean Name - If the bean implements BeanNameAware interface, spring


passes the bean's id to setBeanName() method.

 Set Bean factory - If Bean implements BeanFactoryAware interface, spring


passes the beanfactory to setBeanFactory() method.

 Pre Initialization - Also called postprocess of bean. If there are any bean
BeanPostProcessors associated with the bean, Spring calls
postProcesserBeforeInitialization() method.

 Initialize beans - If the bean implements IntializingBean,its


afterPropertySet() method is called. If the bean has init method declaration,
the specified initialization method is called.

 Post Initialization - If there are any BeanPostProcessors associated with


the bean, their postProcessAfterInitialization() methods will be called.

 Ready to use - Now the bean is ready to use by the application.

 Destroy - If the bean implements DisposableBean , it will call the destroy()


method .

What is Spring Security ?


Spring security is a project under spring framework umbrella, which provides
support for security requirements of enterprise Java projects. Spring Security
formerly known as aegis security provides out of box support for creating login
screen, remember me cookie support, securing URL, authentication provider to
authenticate user from database, LDAP and in memory, concurrent active session
management support and many more. In order to use Spring security in a Spring
MVC based project, you need to include spring-security.jar and configure it in
application-Context-security.xml file, you can name it whatever you want, but make
sure to supply this to ContextLoaderListener, which is responsible for creating
Spring context and initializing dispatcher servlet.

Can we use more than one configuration file for our Spring project?
Problem
In a large project structure, the Spring’s bean configuration files are located in
different folders for easy maintainability and modular. For example, Spring-
Common.xml in common folder, Spring-Connection.xml in connection
folder, Spring-ModuleA.xml in ModuleA folder…and etc.

You may load multiple Spring bean configuration files in the code :

ApplicationContext context =

new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml",

"Spring-Connection.xml","Spring-ModuleA.xml"});

Put all spring xml files under project classpath.

project-classpath/Spring-Common.xml

project-classpath/Spring-Connection.xml

project-classpath/Spring-ModuleA.xml
Solution

The above ways are lack of organizing and error prone, the better way should be
organized all your Spring bean configuration files into a single XML file. For
example, create a Spring-All-Module.xml file, and import the entire Spring bean
files like this :

File : Spring-All-Module.xml

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<import resource="common/Spring-Common.xml"/>
<import resource="connection/Spring-Connection.xml"/>

<import resource="moduleA/Spring-ModuleA.xml"/>

</beans>

Now you can load a single xml file like this :

ApplicationContext context =

new ClassPathXmlApplicationContext(Spring-All-Module.xml);

Put this file under project classpath.

project-classpath/Spring-All-Module.xml
Note
In Spring3, the alternative solution is using JavaConfig @Import.

Explain Spring MVC flow with a simple example e.g. starting from
Container receives request and forward to your Java application ?

Difference between BeanFactory and ApplicationContext in Spring?

 BeanFactory-Does not support the Annotation based dependency Injection.


 ApplicationContext--Support Annotation based dependency Injection.-
@Autowired, @PreDestroy
 BeanFactory-Does not Support
ApplicationContext- Application contexts can publish events to beans that are
registered as listeners
BeanFactory-Does not support way to access Message Bundle(internationalization
(I18N) 
ApplicationContext-Support internationalization (I18N) messages.
BeanFactory-Doesn’t support.
ApplicationContext-Support  many enterprise services such JNDI access, EJB
integration, remoting.
BeanFactory-By default its support Lazy loading
ApplicationContext-- its By default support Aggresive loading.

You might also like