0% found this document useful (0 votes)
80 views

6 Hybris Spring

J2EE is a collection of Java APIs that can be used to build server-side applications. It includes APIs for web and enterprise applications. Spring is a popular framework for building J2EE applications that aims to make development easier through features like dependency injection and aspects. Spring uses inversion of control and dependency injection principles and has modules for core functions, aspects, web applications, data access and testing.

Uploaded by

xogexe2245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

6 Hybris Spring

J2EE is a collection of Java APIs that can be used to build server-side applications. It includes APIs for web and enterprise applications. Spring is a popular framework for building J2EE applications that aims to make development easier through features like dependency injection and aspects. Spring uses inversion of control and dependency injection principles and has modules for core functions, aspects, web applications, data access and testing.

Uploaded by

xogexe2245
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

J2EE (Java 2 Enterprise Edition)

J2EE is a collection of Java APIs owned by Oracle that software developers can use to write server-side
applications. It was formerly known as Java 2 Platform, Enterprise Edition, or J2EE.

Java EE applications are hosted on application servers, such as IBM's WebSphere, Weblogic, Oracle's GlassFish
or Red Hat's WildFly server, all of which run either in the cloud or within a corporate data center.

J2EE Archictecture

Spring

• Is an open source application framework that aims to make J2EE development easier
• Development made easier with these concepts / techniques
➢ IoC & DI = Promotes loose coupling
➢ POJO = Lightweight, easy testing
➢ AOP = Promotes separation of concerns, maintainability etc.
➢ Templates = Provides a standard programming model which does the heavy lifting for you
➢ Spring WEB framework has a well-designed web MVC framework

Spring Framework History


• Spring framework was written by Rod Johnson along with a book in 2002.
• Spring 1.0 – 2004 – All core features
• Spring 2.0 – 2006 - Simplified the XML config files
• Spring 2.5 – 2007 - Introduced annotation configurations
• Spring 3.2 - 2012 - Introduced Java configuration, had support for Java 7, Hibernate 4, Servlet 3.0, and
also required a minimum of Java 1.5.
• Spring 4.0 - 2014 - Support for Java 8, deprecated packages, classes & methods removed
• Spring 4.3 – 2016 – Improvements to core container, caching, JMS, Web Socket, testing etc.
• Spring Boot 1.0 – 2014 – Stand alone, Convention over Configuration,
• Spring Boot 1.5 – 2017 – Improvement to integration with Cloud Foundry, LDAP support, a loggers
endpoint, and Apache auto-configuration support

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


Feature of Spring

JDK 9  Spring 5.0  Spring Boot 2.0  Spring IO platform (Spring IO foundation + Spring IO execution layers)

Spring Framework Architecture

Spring is one-stop shop for all your enterprise applications. However, Spring is modular, allowing you to pick
and choose which modules are applicable to you, without having to bring in the rest.

What are the layers in spring framework?


(1)Core (2) AOP (3) Web (4) Data Access / Integration (5) Test

What are the modules in Core Container / Core Layer?


(1) Beans (2) Core (3) Context (4) SPEL (Spring Expression Language).

Beans = Provides BeanFactory, which is implemenation of factory pattern ( factory pattern is used to create
instances of different classes of same)
Core = Provides IoC (Inversion of Control) & DI (Dependency Injection)
Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)
Context = Provides the implementation of ApplicationContext. It uses Beans and Cores module
Expression Language = Used for querying and manipulating objects at runtime

AOP (Aspect Oriented Programming) module = AOP allows to define interceptors and point-cuts to seprate
code as required.
Ascepts module = supports integration with AspectJ, which is again a powerful AOP framework.
Instrumenation module = Instumentation is the ability to monitor the level of products performance, to
diagnose the errors and write the trace information

What are the modules in Data Access / Integration?


(1) JDBC ( Java Database Connectivity) = Provides JDBC abstraction layer that removes the need for tedious
JDBC related coding ( JDBC code can be done using JdbcTemplate)
(2) ORM (Object Relational Mapping) = Provides integration layers for object relational mapping APIs, such
as JPA, JDO, Hibernate & iBatis
(3) OXM (Object XML Mapping) = Provides an abstraction layer that supports object / XML mapping
implementations for JAXB, Castor,XMLBeans, JiBX & XStream
(4) JMS (Java Message Service) = Contains features for Produce and Consume messages
(5) Transactions = Supports both programmatic and declarating transaction management. Programmatic is
handling in the program and declarative is handling either as part of annotations or using XML.
What are the modules in Web layer?

Web = Provides support for features like multipart file upload, initialization of the IoC container using servlet
listeners, application context etc.
Servlet (spring-web-mvc) = Provides MVC implementation for web applications.
Portlet (spring-webmvc-portlet) = Provides the support for spring based portlets
Test = Supports to test the spring modules using junit frame work

What are spring beans?

Spring beans are objects which are created and managed completely by spring container. Spring container
manages the life cycle of beans (initializing, creating, destroying etc.)

What are the different types of spring framework containers?

(1) BeanFactory Container


o Simple container and provides the basic support for DI.
o Lazy loading
o Instantiate the bean and manages the life cycle of bean when you call getBean(“abc”)
o BeanFactory factory = new XmlBeanFactory (new ClassPathResource("SpringBeans.xml"));
o Does not supports internalization (I18N)
o Deprecated
(2) ApplicationContext Container
o Instantiates singleton beans when the container is started and manages the life cycle of beans
o Aggressive loading

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


o Supports internalization (I18N)
o ApplicationContext provides all the features of BeanFacotry + some enterprise specific features
such as JNDI access, AOP, Transactions, EJB integration, remoting etc.
o ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");
IOC (Inversion of Control) = 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. The
container manages the entire life cycle of beans.

DI (Dependency Injection) = Dependency Injection is a design pattern on which dependency of object is injected
by framework rather than created by Object itself.

Dependency Injection reduces coupling between multiple objects as its dynamically injected by framework

One of the implementation of DI is Inversion of Control (IOC) on which framework like Spring controls object’s
dependency.

We have 2 types of Dependency injection

1) Constructor Injection = The container invokes a class constructor with a number of arguments, each
representing a dependency on other class.
2) Setter/Getter Injection = The container calling setter methods on your beans after invoking a no-
argument constructor to instantiate your bean.

When to use constructor based Injection and when to use setter based injection?

To make it simple, we can use constructor based dependency injection for mandatory dependencies and setter
based injection for optional dependencies. It is a rule of thumb!!

For example - If you want to instantiate a class, you always do it with its constructor. So if you are using
constructor based injection, the only way to instantiate the class is through that constructor. If you pass the
dependency through constructor it becomes evident that it is a mandatory dependency.

On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class
variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the
dependency through setter method of a class it implicitly means that it is an optional dependency.

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


MVC Architecture

Model = Represents data (The model encapsulates the application data & in general they will consist of POJO)

View = Represents UI part (The view is responsible for rendering the model data and in general it generates
HTML output that the client’s browser can interrupt)

Controller = Manages the application flow (The controller is responsible for processing user requests and
building an appropriate model and passed it to the view for rendering)

Spring MVC architecture

Spring WEB framework has a well-designed web MVC framework

Step 1= First http request will be received by DispatcherServlet


Step 2 = DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name
associated with the given request (based on the URL)
Step 3 = So request transfer to the Controller, and then controller will process the request by executing
appropriate methods and returns ModeAndView object (contains Model data and View name) back to the
DispatcherServlet
Step 4 = Now DispatcherServlet send the view name to the ViewResolver to get the actual view page
Step 5 = Finally DispatcherServlet will pass the Model object to the View page to display the result

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


What are the Spring Bean Scopes?

Singleton = Only one per spring container (means spring creates only one object during application context
initialization). Same object is used. This is default and by default all the beans in spring are singleton.

Prototype = New bean created with every request or reference. The bean created when the getBean(“..”) is
called not during initialization.

Web-aware context bean scopes = Spring ties very well with web application (ex- JSP, Servlet). You can tie bean
scopes to the request and session.

request = New bean created per servlet request

session = New bean created per session

global session = New bean per global HTTP Session (portlet context).

application = New bean for the entire application.

What is the difference between prototype and request scope?

Prototype creates a brand-new instance every time you call getBean on the ApplicationContext. Whereas for
Request, only one instance is created for an HttpRequest. So in a single HttpRequest, I can call getBean twice on
Application and there will ever be one bean instantiated, whereas that same bean scoped to Prototype in that
same single HttpRequest would get 2 different instances.

HttpRequest scope
Mark mark1 = context.getBean("mark"); Mark mark2 = context.getBean("mark");
mark1 == mark2; //This will return true
Prototype scope
Mark mark1 = context.getBean("mark"); Mark mark2 = context.getBean("mark");
mark1 == mark2; //This will return false
Autowiring = Autowire is an easy way of doing dependency injection

Dependency injection without autowiring

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


If you see above YahooAddressService depends on addressDao and addressValidator objects. If you want to add
another dependency then you need to add one more property like above.
To avoid modifying the xml each time for dependency, we can use spring feature “Autowiring”
What are the different types of autowriting?

(1) byName (2) byType (3) constructor (4) default

byName = Spring container looks for bean name / id same as property name of the class for autowiring

Note = if you notice above xml the properties are removed because of autowire=”byName”

byType = Spring container selects the bean by class type for autowiring (The data type of the attribute should
be same as the data type of the bean defined in the spring configuration file)

constructor = spring searches for the type of constructor argument inside spring configuration file

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


default = Spring searches for the bean by constructor. If there is no matching constructor then it will search
based on bytype

Note = You can specify autowire for all beans using a single tag “default-autowire” some thing like this.

All the 3 beans have autowire feature enabled by “bytype”


What are the different ways to configure Dependency Injection?

Spring frame work provides 3 main ways to confiure  (1) XML (2) Annotations (3) Java-based configuration

Annotation based configuration

• Starting from spring 2.5 version the Dependency Injection can be done using annotations.
• Annotation injection is performed before xml injection
• Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-
based wiring, we will need to enable it in our Spring configuration
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>

@Autowired = Can apply to constructor, bean property setter method, any method & property

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


Note = @Autowired(required=false) – means bean dependency is optional
@Required = Annotation applies to bean property setter methods & any method
@Qualifier = Annotation along with @Autowired can be used to remove the confusion by specifiying which
exact bean will be wired
@Resource = can apply to bean property setter method, any method & property (This is a JSR-250 annotation
and spring supports it)

What is the difference between <context:annotation-config> vs <context:component-scan>?

<context:annotation-config> = Used to activate applied annotations in already registered beans in application


context.
<context:component-scan> = Does what <context:annotation-config>does + additionally it scans the packages
and register the beans in application context.

Java based configurations

Java-based configuration option enables you to write most of your Spring configuration without XML but with
the help of few Java-based annotations.

@Configuration = Annotating a class with this indicates the class can be used by the Spring IoC container as a
source of bean definitions

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


@Bean annotations = Method annotated with this will return an object that should be registered as a bean in
the Spring application context.

How spring container know what beans need to register?

Spring scans all the beans that has annoted with @Component, @Service, @Controller, @Repository etc.

@Component Generic and can be used across application


@Serivce Annotate classes at service layer
@Controller Annotate classes at presentation layers. Mainly used in spring MVC
@Repository Annotate classes at persistency layer

Can we just use @Component for all the components ( means instead of @Service, @Controller,
@Repository) for auto scanning in all layers?

Yes, you can use @Component and spring will scan all your components but is not good practice. For readibility
and understandable you need to use @Service, @Controller, @Repository for specific layers.

What is the difference between @Autowired, @Resource & @Inject?

Annotation Lookup hierarchy Package


@Autowired Matches by Type org.springframework.beans.factory.annot
Matches by Qualifier ation.Autowired
Matches by Name
@Inject Matches by Type javax.inject.Inject (from JSR-330)
Matches by Qualifier
Matches by Name
@Resource Matches by Name javax.annotation.Resource (from JSR-250)
Matches by Type
Matches by Qualifier

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


When you want to specify the name here is how you can do..

What is the difference between bean name vs bean id in the xml configuration file?

Both id and name used to uniquely identify a bean. If you a bean have more than one name then it is considered
as alias. Usability of alias is in the case where application is too large and we want loose coupling of even bean
names among each other.

<bean id =”abc” class=”com.Test />


(1) only one Id is allowed
(2) bean id’s won’t allow special charaters like #,@, /, * etc. If you add one of these special characters to the
id, you get an XmlBeanDefinitionStoreException thrown when the configuration is read by the
container. The exception indicates the id “is not a valid value for ‘NCName’.”

<bean name=”abc” class =”com.Test />


(1) multiple names allowed ( name attribute allows multiple aliases)
(2) bean name allows special charaters and these special characters are helpful for certain types mapping.
Example – “/” character is useful in identifying certain beans in MVC and RESTFul situations.
<bean id =”test” name=”test1,test2,test3” class=”com.Testing” />
You can retrive the bean using id or names like this. The container returns same Testing instance in each of
these cases.

Testing t1 = (Testing) context.getBean("test");


Testing t2 = (Testing) context.getBean("test1");
Testing t3 = (Testing) context.getBean("test2");
Testing t4 = (Testing) context.getBean("test3");

What happens if you have same bean name in different xml files ( lets say beans1.xml & beans2.xml)?
Beans1.xml = <bean id=”test” name=”test1, test2” class=”com.Testing” />
Beans2.xml = <bean id=”abc” name=”xyz, test2” class=”com.Hello” />

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(new String[] { "beans2.xml",


"beans1.xml" });
Testing t = (Testing) context.getBean("test2");

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(new String[] { "beans1.xml",


"beans2.xml" });
Hello t = (Hello) context.getBean("test2");

The documenation says the last bean definition with the same id or name wins.

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)


What is the difference between @Controller vs @RestController?
@Controller = Is used to mark classes as Spring MVC Controller
@RestController = Is @Controller + @ResponseBody (return value should be bound to the web response body)

What is @Profile?
@Profile – used to execute a perticular class / method against dev, test, prod etc. For example in dev we may
need to use Mock mail server and in production need to use SMTP server for sending mails. You can define the
enviornment in the properties file and then annotate with @profile at method level or class level etc.
Request Related Annotations

@RequestMapping = Used to map web requests onto specific handler classes and / or handler methods

Examples = Class level = @RequestMapping(“/training”)

Method level = @RequestMapping(method =RequestMethod.GET)

@RequestMapping(method =RequestMethod.POST)

@RequestMapping(value =”/login”, method =RequestMethod.GET)

@RequestMapping(value =”/login”, method =RequestMethod.POST)

@RequestParam  Sometimes we get parameters in the request URL, mostly in GET requests. We can use
@RequestMapping with @RequestParam annotation to retrieve the URL parameter and map it to the method
argument.

@ResponseBody  Used to send the response to the web request

@RequiredHardLogin  Custom annotation written in hybris for validating the request is secure or not before
continuing the request.

@PathVariable  Used where the data is fetched dynamically depending on the URL

For example, consider an e-commerce website where all the products under a particular category has to be
retrieved

What is the difference between @RequestParam vs @PathVariable?

@RequestParam used for accessing the values of the query parameters whereas @PathVariable used for
accessing the values from the URI template.

URI template  is a way to specify a URL that includes parameters that must be substituted before the URL is
resolved. It’s a part of URL containing variable names enclosed in braces
example - www.example.com/user/{id}.

Contact us for more information  [email protected] (Java–Salesforce–SAP Portal–UI5/Fiori–Hybris)

You might also like