Autowiring a Spring Bean from a JSF Controller - spring

I receive NullPoin Exception while calling any method of a Spring Bean, as it seems it is not injected in the container. And I can' t understand why.
Th particularity is that the Controller is using JSF and the Beans are Spring Bean: may be is this the problem? Or just configuration mistake?
The (simplified) code and config is:
Context.xml (called from root context)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:plugin="http://www.springframework.org/schema/plugin"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/plugin http://www.springframework.org/schema/plugin/spring-plugin.xsd">
<!--===========LANGUAGE_TO_LOCALE SERVICE CONFIG BEGIN===========-->
<bean
id="languagesCountryLocaleHelper"
class="com.i18n.MyControllerHelper"
scope="request" />
</beans>
JSF COntroller:
#RequestScoped
#Named
public class MyController {
#Autowired
private MyControllerHelper helper;
public void doSomething() {
helper.doSomething ();
}
}
MyControllerHelper:
#Component
public class MyControllerHelper {
public void doSomething() {
// do something useful
}
}
So, this is the simplified case.. do you have any idea on where my error can be?
Thank you in advance!

#Autowired
private MyControllerHelper helper = new MyControllerHelper();
change to this
#Autowired
private MyControllerHelper languagesCountryLocaleHelper;

I solved the problem injecting MyControllerHelper through:
helper = AppContext.getBean(MyControllerHelper.class);
After that, the bean is instantiated and injected and at cascade all the other beans after it.
I suppose it was due by the fact as JSF Controller the Controller instance Object was in a different container now automatically aware of Spring Beans.

Related

Aspect not working witha spring bean

I am trying to create a simple aspect .
Here is my simple spring bean
public class SimpleService {
public void sayHello(){
System.out.println("hi");
}
}
Here is my aspect class
#Aspect
public class SimpleAspect {
#Before("execution(void sayHello())")
public void entering(){
System.out.println("entering..");
}
}
Here is my configuration 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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<aop:aspectj-autoproxy/>
<bean id="service" class="com.schatt.service.SimpleService"></bean>
My understanding was that when I try to invoke SimpleService.sayHello() , the before aspect will be called and after that sayHello() will be called.But the aspect is not getting triggered.Can not understand what I am missing here.
The aspect needs to be created by Spring (in oder to apply the proxying).
<bean id="simpleAspect" class="package-name.SimpleAspect"></bean>
If your class does not implement any interface, you will have to use <aop:aspectj-autoproxy proxy-target-class="true"/>
In addition to what manish and fateddy have said, please also note that SimpleService needs to be a Spring #Component in order to make it work with Spring AOP.

Problems with #Autowire annotation (null)

I have problems with two services that i autowired in a validator class. The services works ok because in my controller are autowired. I've an applicationContext.xml file and MyApp-servlet.xml file. My base package is es.unican.meteo and i have problems with the package es.unican.meteo.validator. The package es.unican.meteo.controller and es.unican.meteo.service can autowire the services properly.
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
....
some beans
...
</beans>
Myapp-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- Enabling Spring beans auto-discovery -->
<context:component-scan base-package="es.unican.meteo" />
<!-- Enabling Spring MVC configuration through annotations -->
<mvc:annotation-driven />
Class ResetPasswordValidator:
package es.unican.meteo.validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import es.unican.meteo.model.User;
import es.unican.meteo.service.MessageService;
import es.unican.meteo.service.UserService;
public class ResetPasswordValidation implements Validator{
#Autowired
private UserService userService;
#Autowired
private MessageService messageService;
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
User user = (User)target;
if(userService.getUserByEmail(user.getEmail())==null){
errors.rejectValue("email", messageService.getMessage("app.error.nonexistentemail"));
}
}
}
I can see the controllers, services and autowired elements in the Spring elements. It seems like spring is not detecting the autowired properties in the package validator. Any ideas?
Edit: Log of the ResetPasswordValidation (Autowire fields)
12:48:50,697 DEBUG main support.DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'resetPasswordValidation'
12:48:50,697 DEBUG main support.DefaultListableBeanFactory:430 - Creating instance of bean 'resetPasswordValidation'
12:48:50,701 DEBUG main annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.validator.ResetPasswordValidation]: AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.validator.ResetPasswordValidation.userService
12:48:50,702 DEBUG main annotation.InjectionMetadata:60 - Found injected element on class [es.unican.meteo.validator.ResetPasswordValidation]: AutowiredFieldElement for private es.unican.meteo.service.MessageService es.unican.meteo.validator.ResetPasswordValidation.messageService
12:48:50,702 DEBUG main support.DefaultListableBeanFactory:504 - Eagerly caching bean 'resetPasswordValidation' to allow for resolving potential circular references
12:48:50,707 DEBUG main annotation.InjectionMetadata:85 - Processing injected method of bean 'resetPasswordValidation': AutowiredFieldElement for private es.unican.meteo.service.UserService es.unican.meteo.validator.ResetPasswordValidation.userService
Make sure you annotate the class so Spring picks it up as a bean. Autowiring can only occur on beans/classes managed by the DI container.
Adding #Component will cause the class to be picked up by Spring's component scanning, causing ResetPasswordValidation to become a bean. At this point, it should be eligible to have fields autowired.
#Component
public class ResetPasswordValidation implements Validator

Set resource annotated field of a class in unit tests

I have a class.
public class Definitions{
#Resource(name="schemas")
private Collection<String> schemas;
}
This class is initialized via spring.
Spring file:test.xml
<util:list id="schemas">
<value>"A"</value>
<value>"b"</value>
</util:list
<bean id="Definitions" />
Is there some way I can insert value to private field schemas(annotated with Resource) in my unit test without using spring. I tried using setting private variable via Reflection but that also did not help(probably due to security restrictions).
Even using spring,
ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
It is not able to load schemas in Definitions bean. I get "NullPointerException" while accessing schemas.
Add a setter for it:
public class Definitions{
private Collection<String> schemas;
#Resource(name="schemas")
public void setSchemas(Collection<String> schemas) {
this.schemas = schemas;
}
}
This is the principle of dependency injection: you inject dependencies manually, vis constructor or setter injection, in your unit tests.
Try to do the following:
Insert the list in you spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<util:list id="listTest">
<value>Valor 1</value>
<value>Valor 2</value>
</util:list>
</beans>
Reference the list in your code:
#Resource(name = "listTest")
private List<String> listTest;
I've tested here and it works fine on Spring 4 and 3, there's no need to implement a setter method.

Inject property to spring bean using annotation

As explained here and here it is quite clear how to do it but still can't seem to make it work.
I simply like to use the #Value annotation in order to inject a property to a spring bean. I created a basic spring MVC project with one controller and one bean.
Here is my application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="me.co.fatsecret" />
<!-- Properties -->
<bean id="props"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:fatProperties.properties" />
</bean>
</beans>
I have one bean called Configuration:
package me.co.fatsecret;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class Configuration {
/*--- Members ---*/
#Value("${api_key}")
protected String API_KEY;
#Value("${api_secret}")
protected String API_SECRET;
#Value("${api_url}")
protected String API_URL;
/*--- Constructors ---*/
public Configuration() {
}
/*--- Getters & Setters ---*/
public String getAPI_KEY() {
return API_KEY;
}
public void setAPI_KEY(String aPI_KEY) {
API_KEY = aPI_KEY;
}
public String getAPI_SECRET() {
return API_SECRET;
}
public void setAPI_SECRET(String aPI_SECRET) {
API_SECRET = aPI_SECRET;
}
public String getAPI_URL() {
return API_URL;
}
public void setAPI_URL(String aPI_URL) {
API_URL = aPI_URL;
}
}
Now I have only one controller, injected with this Configuration class and as I call this controller I see that the values in the Configuration class are not populated right.
My properties file is located under the resources folder (src/main/resources) and is a part of my classpath (done by default since this is a maven project). Here it is:
api_url=http://platform.fatsecret.com/js?
api_key=SomeKey
api_secret=SomeSecret
The file name is fatProperties.properties.
As I debug my server when calling the controller I see that the content of the Configuration class is:
${api_key}
${api_secret}
${api_url}
This is the actual value of the Strings, wich means that the vales from the properties file are not getting injected for some reason.
Am I missing something here?
UPDATE1: I replaced the PropertyPlaceholderConfigurer bean with:
<context:property-placeholder location="classpath:fatProperties.properties"/>
Getting the same result
Ok, got it!
I'm using a spring MVC project, which means I have a separated context for my web layer (the controllers). The "Configuration" bean which hods the properties using the #Value annotation is injected to a controller. My property-placeholder is defined within my root-context hence it cannot be seen from my controller. To resolve the issue I simply added the property-placeholder definition to my DispatcherServlet context and it works like a charm :)
Add this to your application context file:
<context:property-placeholder location="classpath:fatProperties.properties" />
Try
#Value("#{props['api_key']}")
private String apiKey;

implement AOP for Controllers in Spring 3

How do I implement AOP with an annotated Controller?
I've search and found two previous posts regarding the problem, but can't seem to get the solutions to work.
posted solution 1
posted solution 2
Here's what I have:
Dispatch Servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.foo.controller"/>
<bean id="fooAspect" class="com.foo.aop.FooAspect" />
<aop:aspectj-autoproxy>
<aop:include name="fooAspect" />
</aop:aspectj-autoproxy>
</beans>
Controller:
#Controller
public class FooController {
#RequestMapping(value="/index.htm", method=RequestMethod.GET)
public String showIndex(Model model){
return "index";
}
}
Aspect:
#Aspect
public class FooAspect {
#Pointcut("#target(org.springframework.stereotype.Controller)")
public void controllerPointcutter() {}
#Pointcut("execution(* *(..))")
public void methodPointcutter() {}
#Before("controllerPointcutter()")
public void beforeMethodInController(JoinPoint jp){
System.out.println("### before controller call...");
}
#AfterReturning("controllerPointcutter() && methodPointcutter() ")
public void afterMethodInController(JoinPoin jp) {
System.out.println("### after returning...");
}
#Before("methodPointcutter()")
public void beforeAnyMethod(JoinPoint jp){
System.out.println("### before any call...");
}
}
The beforeAnyMethod() works for methods NOT in a controller; I cannot get anything to execute on calls to controllers. Am I missing something?
In order to put an aspect on a HandlerMethod in a class annotated with #Controller in Spring 3.1 you need to have the proxy-target-class="true" attribute on the aspectj-autoproxy element. You also need to have the CGLIB and the ASM libraries as a dependency in your WAR/EAR file. You can either specify your annotated aspect class as a bean and use the aop:include as stated above or you can leave the aop:include out and add a filter similar to this in your component scan element:
<context:component-scan>
<context:include-filter type="aspectj"
expression="com.your.aspect.class.Here"/>
</context:component-scan>
I do not know if this is a requirement as a result of Spring 3.1 only but I know that without this, you will not be able to put an aspect on your controller HandlerMethod. You would get an error similar to:
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
HandlerMethod details:
Controller [$Proxy82]
Method [public void com.test.TestController.testMethod(java.security.Principal,javax.servlet.http.HttpServletResponse) throws javax.servlet.ServletException]
Resolved arguments:
[0] [null]
[1] [type=com.ibm.ws.webcontainer.srt.SRTServletResponse] [value=com.ibm.ws.webcontainer.srt.SRTServletResponse#dcd0dcd]
This is not required if your aspect is on a method in a class that is not a controller
I am going to state an alternative solution (sorry not a direct answer) but what you wanting to do is probably best done via interceptors and filters.

Resources