Spring Security Framework Focuses On Providing Both Authentication and Authorization in Java Applications. It Also Takes Care of Most of The Common Security Vulnerabilities Such As CSRF Attack
Spring Security Framework Focuses On Providing Both Authentication and Authorization in Java Applications. It Also Takes Care of Most of The Common Security Vulnerabilities Such As CSRF Attack
Spring Security Framework Focuses On Providing Both Authentication and Authorization in Java Applications. It Also Takes Care of Most of The Common Security Vulnerabilities Such As CSRF Attack
business operations. On one side of the service layer, you have calls to CRUD methods and whatever
other resources you need to fulfil service requests. On the other side of the service layer, you have
methods that execute business transactions:
http://www.journaldev.com/2696/spring-interview-questions-and-answers
http://stackoverflow.com/questions/25997438/no-session-found-for-current-thread-in-junit-for-dao-layer
https://dzone.com/articles/bean-validation-made-simple
1.
Spring security framework focuses on providing both authentication and authorization in java
applications. It also takes care of most of the common security vulnerabilities such as CSRF
attack.
Its very beneficial and easy to use Spring security in web applications, through the use of
annotations such as @EnableWebSecurity. You should go through following posts to learn how
to use Spring Security framework.
1.
Spring is one of the most widely used Java EE framework. Spring framework core concepts
are Dependency Injection and Aspect Oriented Programming.
Spring framework can be used in normal java applications also to achieve loose coupling
between different components by implementing dependency injection and we can perform
cross cutting tasks such as logging and authentication using spring support for aspect
oriented programming.
I like spring because it provides a lot of features and different modules for specific tasks such
as Spring MVC and Spring JDBC. Since its an open source framework with a lot of online
resources and active community members, working with Spring framework is easy and fun at
same time.
2.
Spring Framework is built on top of two design concepts Dependency Injection and Aspect
Oriented Programming.
Some of the features of spring framework are:
Lightweight and very little overhead of using framework for our development.
Spring IoC container manages Spring Bean life cycle and project specific
configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful
web services capable of returning XML as well as JSON response.
Writing unit test cases are easy in Spring framework because our business logic
doesnt have direct dependencies with actual resource implementation classes. We can
easily write a test configuration and inject our mock beans for testing purposes.
Reduces the amount of boiler-plate code, such as initializing objects, open/close
resources. I like JdbcTemplate class a lot because it helps us in removing all the boilerplate code that comes with JDBC programming.
Spring framework is divided into several modules, it helps us in keeping our
always on top of the new technologies, for example there is a Spring project for Android
to help us write better code for native android applications. This makes spring
framework a complete package and we dont need to look after different framework for
different requirements.
3.
Dependency Injection design pattern allows us to remove the hard-coded dependencies and
make our application loosely coupled, extendable and maintainable. We can implement
dependency injection pattern to move the dependency resolution from compile-time to
runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate
Code reduction, Configurable components and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency
Injection to automate the process of dependency injection. But in most of the cases we are
looking for more than just dependency injection and thats why Spring is the top choice for
this.
4.
We can use Spring XML based as well as Annotation based configuration to implement DI in
spring applications. For better understanding, please read Spring Dependency Injection
example where you can learn both the ways with JUnit test case. The post also contains
sample project zip file, that you can download and play around to learn more.
5.
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However STS
comes with Eclipse with some other important stuffs such as Maven support, Templates for
creating different types of Spring projects and tc server for better performance with Spring
applications.
I like STS because it highlights the Spring components and if you are using AOP pointcuts and
advices, then it clearly shows which methods will come under the specific pointcut. So rather
than installing everything on our own, I prefer using STS when developing Spring based
applications.
6.
7.
Enterprise applications have some common cross-cutting concerns that is applicable for
different types of Objects and application modules, such as logging, transaction
management, data validation, authentication etc. In Object Oriented Programming,
modularity of application is achieved by Classes whereas in AOP application modularity is
achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible
in normal object oriented programming. For example, we can have a separate class for
logging but again the classes will have to call these methods for logging the data. Read more
about Spring AOP support at Spring AOP Example.
8.
annotation.
Advice: Advice is the action taken for a particular join point. In terms of programming, they
are methods that gets executed when a specific join point with matching pointcut is reached
in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that is matched with join points to determine
whether advice needs to be executed or not. Pointcut uses different kinds of expressions that
are matched with the join points. Spring framework uses the AspectJ pointcut expression
language for determining the join points where advice methods will be applied.
Join Point: A join point is the specific point in the application such as method execution,
exception handling, changing object variable values etc. In Spring AOP a join points is always
the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use args()
expression in the pointcut to be applied to any method that matches the argument pattern. If
we use this, then we need to use the same name in the advice method from where argument
type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example
then you can easily relate to them.
9.
Spring AOP is simpler to use than AspectJ because we dont need to worry about the
weaving process.
Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then
working with Spring AOP is easier.
Spring AOP supports only proxy-based AOP, so it can be applied only to method
execution join points. AspectJ support all kinds of pointcuts.
One of the shortcoming of Spring AOP is that it can be applied only to the beans
dependencies.
Some of the useful ApplicationContext implementations that we use are;
AnnotationConfigApplicationContext:
based configuration.
ClassPathXmlApplicationContext:
configuration.
FileSystemXmlApplicationContext:
the xml configuration file can be loaded from anywhere in the file system.
11.
AnnotationConfigWebApplicationContext
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use
Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any
required dependencies in the bean.
12.
We use Spring Bean configuration file to define all the beans that will be initialized by Spring
Context. When we create the instance of Spring ApplicationContext, it reads the spring bean
xml file and initialize all of them. Once the context is initialized, we can use it to get different
bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view
resolvers and other elements to support annotations based configurations.
13.
Java Based Configuration: If you are using only annotations, you can configure a
Spring bean using @Bean annotation. This annotation is used with @Configuration classes to
configure a spring bean. Sample configuration is:
@Configuration
@ComponentScan(value="com.journaldev.spring.main")
@Bean
To get this bean from spring context, we need to use following code snippet:
singleton: Only one instance of the bean will be created for each container. This is
the default scope for the spring beans. While using this scope, make sure spring bean
doesnt have shared instance variables otherwise it might lead to data inconsistency
issues because its not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however its meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the
times we are good with the scopes provided by the framework.
To set spring bean scopes we can use scope attribute in bean element or @Scope
annotation for annotation based configurations.
C) What is Spring Bean life cycle?
Spring Beans are initialized by Spring Container and all the dependencies are also injected.
When context is destroyed, it also destroys all the initialized beans. This works well in most of
the cases but sometimes we want to initialize other resources or do some validation before
making our beans ready to use. Spring framework provides support for post-initialization and
pre-destroy methods in spring beans.
We can do this by two ways by implementing InitializingBean and DisposableBean interfaces or
using init-method and destroy-method attribute in spring bean configurations. For more
details, please read Spring Bean Life Cycle Methods.
D) How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
ServletConfig.
They will work only in servlet container specific environment only though.
@Autowired
ServletContext servletContext;
The process of injection spring bean dependencies while initializing it called Spring Bean
Wiring.
Usually its best practice to do the explicit wiring of all the bean dependencies, but spring
framework also supports autowiring. We can use @Autowired annotation with fields or
methods for autowiring byType. For this annotation to work, we also need to enable
annotation based configuration in spring bean configuration file. This can be done by
context:annotation-config element.
For more details about @Autowired annotation, please read Spring Autowire Example.
F) What are different types of Spring Bean autowiring?
autowire byName
autowire byType
autowire by constructor
Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire
by constructor or byType. For more details about these options, please read Spring Bean
Autowiring.
G) Does Spring Bean provide thread safety?
The default scope of Spring bean is singleton, so there will be only one instance per context.
That means that all the having a class level variable that any thread can update will lead to
inconsistent data. Hence in default mode spring beans are not thread-safe.
However we can change spring bean scope to request, prototype or session to achieve
thread-safety at the cost of performance. Its a design decision and based on the project
requirements.
H) What is a Controller in Spring MVC?
Just like MVC design pattern, Controller is the class that takes care of all the client requests
and send them to the configured resources to handle it. In Spring MVC,
org.springframework.web.servlet.DispatcherServlet
@Component is used to indicate that a class is a component. These classes are used for auto
detection and configured as bean, when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with
RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a
mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern
implementation classes.
@Service is used to indicate that a class is a Service. Usually the business facade classes that
provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are
provided so that you can easily distinguish the purpose of the annotated classes.
is the front controller in the Spring MVC application and it loads the spring
bean configuration file and initialize all the beans that are configured. If annotations are
enabled, it also scans the packages and configure any bean annotated with
@Controller, @Repository
ContextLoaderListener
@Component,
or @Service annotations.
Its important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the
ServletContext
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views
directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
InternalResourceViewResolver
providing the view pages directory and suffix location through the bean properties. So if a
controller handler method returns home, view resolver will use view page located at /WEBINF/views/home.jsp.
StandardServletMultipartResolver
uploading. By default there are no multipart resolvers configured but to use them for
uploading files, all we need to define a bean named multipartResolver with type as
MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver
and pass on a wrapped HttpServletRequest. Then its used in the controller class to get the
file and process it. For a complete example, please read Spring MVC File Upload Example.
Spring MVC Framework provides following ways to help us achieving robust exception
handling.
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEBINF/spring/appServlet/servlet-jdbc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
We can also define multiple root level spring configurations and load it through contextparam. For example;
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</paramvalue>
</context-param>
Another option is to use import element in the context configuration file to import other
configurations, for example:
<beans:import resource="spring-jdbc.xml"/>
P) What is ContextLoaderListener?
ContextLoaderListener is the listener class used to load root context and define spring bean
configurations that will be visible to all other contexts. Its configured in web.xml file as:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Q) What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do following tasks.
Spring bean configuration file to define beans, if using annotations then it has to be
configured here. Also we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC Hello World application.
is the Front Controller in the Spring MVC application that takes care of all the
Spring provides excellent support for localization or i18n through resource bundles. Basis
steps needed to make our application localized are:
or ReloadableResourceBundleMessageSource.
<beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</beans:bean>
<beans:bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
</beans:bean>
<interceptors>
<beans:bean
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
</beans:bean>
</interceptors>
Use spring:message element in the view pages with key names, DispatcherServlet
picks the corresponding value and renders the page in corresponding locale and return
as response.
How can we use Spring to create Restful Web Service returning JSON response?
We can use Spring Framework to create Restful web services that returns JSON data. Spring
provides integration with Jackson JSON API that we can use to send JSON response in restful
web service.
We would need to do following steps to configure our Spring MVC application to send JSON
response:
Adding Jackson JSON dependencies, if you are using Maven it can be done with
following code:
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind-version}</version>
</dependency>
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
return empData.get(empId);
}
You can invoke the rest service through any API, but if you want to use Spring then
we can easily do it using RestTemplate class.
What are some of the important Spring annotations you have used?
@ResponseBody for sending Object as response, usually for sending XML or JSON
data as response.
@PathVariable for mapping dynamic values from the URI to handler method
arguments.
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based
response in restful web services.
Spring provides built-in support for uploading files through MultipartResolver interface
implementations. Its very easy to use and requires only configuration changes to get it
working. Obviously we would need to write controller handler method to handle the
incoming file and process it. For a complete example, please refer Spring File Upload
Example.
Spring supports JSR-303 annotation based validations as well as provide Validator interface
that we can implement to create our own custom validator. For using JSR-303 based
validation, we need to annotate bean variables with the required validations.
For custom validator implementation, we need to configure it in the controller class. For a
complete example, please read Spring MVC Form Validation Example.
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and
process it. We can intercept client request at three places preHandle, postHandle and
afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by
extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an
interceptor to intercept all the client requests or we can configure it for specific URI mapping
too. For a detailed example, please refer Spring MVC Interceptor Example.
Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate
utility class that we can use to avoid bolier-plate code from our database operations logic
such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
For JdbcTemplate example, please refer Spring JDBC Example.
For using servlet container configured JNDI DataSource, we need to configure it in the spring
bean configuration file and then inject it to spring beans as dependencies. Then we can use it
with JdbcTemplate to perform database operations.
Sample configuration would be:
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in
a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport,
JdoDaoSupport
We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are
using Hibernate 3+ where SessionFactory provides current session, then you should avoid
using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with
dependency injection for the integration. Also Spring ORM provides support for using Spring
declarative transaction management, so you should utilize that rather than going for
hibernate boiler-plate code for transaction management. For better understanding you
should go through following tutorials:
Spring security framework focuses on providing both authentication and authorization in java
applications. It also takes care of most of the common security vulnerabilities such as CSRF
attack.
Its very beneficial and easy to use Spring security in web applications, through the use of
annotations such as @EnableWebSecurity. You should go through following posts to learn how
to use Spring Security framework.
We need to define propertyConfigurer bean that will load the properties from the given
property file. Then we can use Spring EL support to inject properties into other bean
dependencies. For example;
<bean id="propertyConfigurer"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location" value="/WEB-INF/application.properties" />
</bean>
<bean class="com.journaldev.spring.EmployeeDaoImpl">
<property name="maxReadResults" value="${results.read.max}"/>
</bean>
If you are using annotation to configure the spring bean, then you can inject property like
below.
@Value("${maxReadResults}")
private int maxReadResults;
Spring Framework is using a lot of design patterns, some of the common ones are:
B.
Avoid version numbers in schema reference, to make sure we have the latest
configs.
For spring beans that are used in multiple contexts in Spring MVC, create them in
the root context and initialize with listener.
For application level properties, best approach is to create a property file and read it
in the spring bean configuration file.
For smaller applications, annotations are useful but for larger applications
annotations can become a pain. If we have all the configuration in xml files, maintaining
it will be easier.
Use correct annotations for components for understanding the purpose easily. For
services use @Service and for DAO beans use @Repository.
Spring framework has a lot of modules, use what you need. Remove all the extra
dependencies that gets usually added when you create projects through Spring Tool
Suite templates.
If you are using Aspects, make sure to keep the join pint as narrow as possible to
avoid advice on unwanted methods. Consider custom annotations that are easier to use
and avoid any issues.
Use dependency injection when there is actual benefit, just for the sake of loosecoupling dont use it because its harder to maintain.
}
Just compare it with the previous implementation of PayServiceImpl class.
There it was tightly coupled with the specific implementation (CashPayment) of the
IPayment interface. In this class it is not tightly coupled with any specific
implementation.
In this class specific implementation is given (injected) in the constructor of the class.
Here the code is loosely coupled as PayServiceImpl is not tied to any specific
implementation, here it only knows the interface which can easily be swapped by
specific implementation at run time as we just saw in point 2
CreditPayment implementation
Here it can be seen that CashPayment and PayServiceImpl are declared as beans in
spring XML configuration. In PayServiceImpl bean, reference of CashPayment is passed as a
constructor argument. With that configuration Spring framework will take care of wiring
the associations and injecting the dependencies needed by an object.
If you want to test and see how it is done this class can be used -
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
IPayService bean = (IPayService) context.getBean("paymentBean");
bean.performPayment();
context.close();
}
}
Constructor Injection
Setter Injection
You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to
use constructor arguments for mandatory dependencies and setters for optional
dependencies.
-----------05/04/2016---------------
@RequestMapping annotation now has a produces and a consumes attributes, specifically for
this purpose:
@RequestMapping(value = "/ex/foos", method = RequestMethod.GET, produces =
"application/json")
@ResponseBody
public String getFoosAsJsonFromREST() {
return "Get some Foos with Header New";
}
@Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component
specialization, so beans marked with it are automatically imported into the DI container. When you add the
@Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs
to instance methods of a class.
@Autowired
EmployeeDAO dao;
public EmployeeDTO createNewEmployee()
{
return dao.createNewEmployee();
}
}
EmployeeController.java
@Controller ("employeeController")
public class EmployeeController
{
@Autowired
EmployeeManager manager;
public EmployeeDTO createNewEmployee()
{
return manager.createNewEmployee();
}
}
EmployeeDTO.java
public class EmployeeDTO {
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
TestSpringContext.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.howtodoinjava.demo.service.EmployeeManager;
public class TestSpringContext
{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
//EmployeeManager manager = (EmployeeManager)
context.getBean(EmployeeManager.class);
//OR this will also work
EmployeeController controller = (EmployeeController)
context.getBean("employeeController");
System.out.println(controller.createNewEmployee());
}
}
Output:
Jan 22, 2015 6:17:57 PM
org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@1b2b2f7f:
startup date [Thu Jan 22 18:17:57 IST 2015]; root of context hierarchy
Jan 22, 2015 6:17:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]