spring interview questions
Top spring frequently asked interview questions
I have a requirement where I need to download a PDF from the website, the PDF needs to be generated within the code, which I thought would be a combination of freemarker and a PDF generation framework like iText (any better way?). However my main problem is how do I allow the user to download a file through a Spring Controller?
Source: (StackOverflow)
Are applicationContext.xml
and spring-servlet.xml
related anyhow in spring framework? Will the properties files declared in applicationContext.xml
be available to DispatcherServlet
? On a related note, why do I need a *-servlet.xml
at all ? Why is applicationContext.xml
alone insufficient?
Source: (StackOverflow)
I'm a little confused as to how the inversion of control (IoC
) works in Spring
.
Say I have a service class called UserServiceImpl
that implements UserService
interface.
How would this be @Autowired
?
And in my Controllers
action, how would I instantiate
an instance
of this service?
Would I just do the following?
UserService userService = new UserServiceImpl();
Source: (StackOverflow)
I'm learning Spring 3 and I don't seem to grasp the functionality behind <context:annotation-config>
and <context:component-scan>
.
From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.
To confuse me even more, there is an annotation-config
attribute on <context:component-scan>
.
Can someone shed some light on these tags? What's similar, what's different, is one superseded by the other, they complete each other, do I need one of them, both?
Source: (StackOverflow)
Should you place the @Transactional
in the DAO
classes and/or their methods or is it better to annotate the Service classes which are calling using the DAO objects? Or does it make sense to annotate both "layers"?
Source: (StackOverflow)
Any ideas what could be the cause of this?
Unable to locate Spring
NamespaceHandler for XML schema
namespace
[http://www.springframework.org/schema/security]
org.springframework.web.context.ContextLoader initWebApplicationContext: Context initialization failed
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]
Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]
This is my applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
...
</beans:beans>
In my pom.xml I have:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-openid</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
Source: (StackOverflow)
I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired
annotation on private member fields.
I have considered using ReflectionTestUtils.setField
but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing.
I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
The error I currently encounter is as follows:
...
Caused by: org...NoSuchBeanDefinitionException:
No matching bean of type [com.package.Dao] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {
@org...Autowired(required=true),
@org...Qualifier(value=dao)
}
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)
If I set the constructor-arg
value to something invalid no error occurs when starting the application context.
Source: (StackOverflow)
I asked a general Spring question: Auto-cast Spring Beans and had multiple people respond that calling Spring's ApplicationContext.getBean()
should be avoided as much as possible. Why is that?
How else should I gain access to the beans I configured Spring to create?
I'm using Spring in a non-web application and had planned on accessing a shared ApplicationContext
object as described by LiorH.
Amendment
I accept the answer below, but here's an alternate take by Martin Fowler who discusses the merits of Dependency Injection vs. using a Service Locator (which is essentially the same as calling a wrapped ApplicationContext.getBean()
).
In part, Fowler states, "With service locator the application class asks for it [the service] explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control.
Inversion of control is a common feature of frameworks, but it's something that comes at a price. It tends to be hard to understand and leads to problems when you are trying to debug. So on the whole I prefer to avoid it [Inversion of Control] unless I need it. This isn't to say it's a bad thing, just that I think it needs to justify itself over the more straightforward alternative."
Source: (StackOverflow)
I am getting the following error when trying to get a JSON request and process it>
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.myweb.ApplesDO]: can not instantiate from JSON object (need to add/enable type information?)
Here is the JSON I am trying to send:
{
"applesDO" : [
{
"apple" : "Green Apple"
},
{
"apple" : "Red Apple"
}
]
}
In Controller , I have the following method signature
@RequestMapping("showApples.do")
public String getApples(@RequestBody final AllApplesDO applesRequest){
// Method Code
}
AllApplesDO is a wrapper of ApplesDO :
public class AllApplesDO {
private List<ApplesDO> applesDO;
public List<ApplesDO> getApplesDO() {
return applesDO;
}
public void setApplesDO(List<ApplesDO> applesDO) {
this.applesDO = applesDO;
}
}
ApplesDO
public class ApplesDO {
private String apple;
public String getApple() {
return apple;
}
public void setApple(String appl) {
this.apple = apple;
}
public ApplesDO(CustomType custom){
//constructor Code
}
}
I am thinking that JACKSON is unable to convert JSON into JAVA objects for sublclasses. Please help with the configuration parameters for JACKSON to convert JSON into JAVA Objects! I am using Spring Framework
EDIT: Included the major bug that is causing this problem in the above sample class - Please look accepted answer for solution.
Source: (StackOverflow)
I am trying to use the org.springframework.orm.jdo.TransactionAwarePersistenceManagerFactoryProxy
in my Spring project, but I am not sure how to use it or whether it's exactly what I am looking for. I realize it can help make my DAOs work with a plain JDO PersistenceManagerFactory
. Another question is: what happens if the proxy doesn't get made properly? Can I still use it to access my factory to create a transaction aware persistence manager? If the object managed by the factory is a singleton, does this change things? Why not just access the PersistenceManagerFactory directly? Perhaps PersistenceManagerFactoryUtils.getPersistenceManager
would be more suited to my needs? Can getObject
return null?
Source: (StackOverflow)
I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?
I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way to configure the app to have the current SecurityContext, or current Authentication, injected instead?
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request...) {
final String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
...
}
Source: (StackOverflow)
I'm working in order to integrate Spring Security SAML Extension with Spring Boot.
I developed a complete sample application, all the source code is published on GitHub:
By running the WebApp as Spring Boot application (through Spring Tool Set, by using an embedded Application Server), it works fine.
Unfortunately, the auth process doesn't work on Undertow/WildFly (and I must use it as production AS).
By logging, I can see that the IdP performs the AuthN process and the instructions of my custom UserDetails
implementation are correctly executed. Despite that Spring doesn't set up the privileges for the current user.
@Component
public class SAMLUserDetailsServiceImpl implements SAMLUserDetailsService {
// Logger
private static final Logger LOG = LoggerFactory.getLogger(SAMLUserDetailsServiceImpl.class);
@Override
public Object loadUserBySAML(SAMLCredential credential)
throws UsernameNotFoundException, SSOUserAccountNotExistsException {
String userID = credential.getNameID().getValue();
if (userID.compareTo("jdoe@samplemail.com") != 0) { // We're simulating the data access.
LOG.warn("SSO User Account not found into the system");
throw new SSOUserAccountNotExistsException("SSO User Account not found into the system", userID);
}
LOG.info(userID + " is logged in");
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
authorities.add(authority);
ExtUser userDetails = new ExtUser(userID, "password", true, true, true,
true, authorities, "John", "Doe");
return userDetails;
}
}
By debugging, I checked that the problem starts from the FilterChainProxy
class.
When I run the webapp on WildFly, I can see that the attribute FILTER_APPLIED
of ServletRequest
is null, thus Spring clears the SecurityContextHolder
.
private final static String FILTER_APPLIED = FilterChainProxy.class.getName().concat(".APPLIED");
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
if (clearContext) {
try {
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
doFilterInternal(request, response, chain);
} finally {
SecurityContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
} else {
doFilterInternal(request, response, chain);
}
}
On VMware vFabric tc Sever and Tomcat that doesn't happen.
Is there a way to resolve this issue?
Source: (StackOverflow)
I have a use case where I need to call a (non-static) method in the bean only-once at the ApplicationContext load up. Is it ok, if I use MethodInvokingFactoryBean for this? Or we have a some better solution?
As a side note, I use ConfigContextLoaderListener to load the Application Context in web application. And want, that if bean 'A' is instantiated just call methodA() once.
How can this be done nicely?
Source: (StackOverflow)
Which annotation, @Resource (jsr250) or @Autowired (Spring specific) should I be using when using DI?
I have successfully used both in the past, @Resource(name="blah")
and @Autowired @Qualifier("blah")
My instinct is to stick with the @Resource tag since it's been ratified by the jsr people. Anyone have strong thoughts on this?
Source: (StackOverflow)
What are the pros and cons of using @Autowired in a class that will be wired up by Spring?
Just to clarify, I'm talking specifically about the @Autowired annotation, not auto-wiring in XML.
I probably just don't understand it, but to me it almost seems like an anti-pattern - your classes start to become aware that they are tied to a DI framework, rather than just being POJOs. Maybe I'm a glutton for punishment, but I like having the external XML config for beans, and I like to have explicit wirings, so I know exactly what is wired where.
Source: (StackOverflow)