RemoteServiceServlet with spring autowired gives nullpointerexception - spring

I'm using GWT with Spring. I encountered the problem of using an #Autowired bean in a RemoteServiceServlet. For some reason this doesn't work automatically and I need to use #Configurable to get this working. I followed this approach but I still get a NullPointerException for the #Autowired bean:
#Configurable
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class AServiceImpl extends RemoteServiceServlet implements AService {
#Autowired
private IABean aBean;
#Override
public void aMethodFromAService(Args arg[]) {
aBean.aMethodOfABean(); // this gives a NullPointerException
}
}
#Component
public class ABean implements IABean {
...
}
Any guidance in what is going on? Any extra information I need to provide?

http://mitosome.blogspot.be/2011/01/injecting-spring-beans-into-gwt.html
Thanks Alexander for putting me in the right direction

You found a workable solution, but just for the record and we have it working as follows:
public class MyServiceImpl extends RemoteServiceServlet
implements MyService, ServletContextAware
{
#Autowired private transient SomeService someService;
....
}
and
<context:annotation-config/>
<context:component-scan base-package="..."/>
The SomeService is a completely vanilla XML-defined bean. Perhaps that or ...implements ServletContextAware makes a difference.
Cheers,

Related

Autowiring of Service and Service Implementation class

Following are my code
#RestController
public class EmployeeController {
#Autowired
EmployeeService empService;
public EmployeeController (EmployeeService Impl empServiceImpl) {
super();
this.empService = empServiceImpl;
}
}
#Service
public interface EmployeeService {
public List<EmployeeDTO> getAllEmployeeDetails()
}
public class EmployeeServiceImpl {
public List<EmployeeDTO> getAllEmployeeDetails(){
//methods business logic and repo call goes here
}
}
When I start my server I am getting below error.
Parameter 1 of constructor in
com.app.in.controller.EmployeeController required a bean of type
'com.app.in.service.EmployeeServiceImpl' that could not be found
My understanding might be wrong. If I annotate the EmployeeSeriveImpl class also with #Service then it working.Is that is the correct way to do it ? My question is the service interface is annotated with #Service still why its implementation is also required to annotation. Please let me know if I miss something in that ? What is the standard method to solve this issue ?
You can get your dependency injected using a constructor. And #Autowired is optional in this case.
This is your example, but with a few corrections:
#RestController
public class EmployeeController {
// private final is a good practice. no need in #Autowire
private final EmployeeService empService;
// this constructor will be used to inject your dependency
// #Autowired is optional in this case, but you can put it here
public EmployeeController (EmployeeService empServiceImpl) {
this.empService = empServiceImpl;
}
}
I assume you have an interface EmployeeService and class EmployeeServiceImpl which implements that interface and is Spring Bean.
Something like this:
#Service
public class EmployeeServiceImpl implements EmployeeService {}
Why this #Service is needed? When you put this annotation on your class, Spring knows this is a bean that Spring should manage for you (container will create an instance of it and inject it wherever it is needed).
Check Spring docs to get more details about Dependency Injection.
The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null.

Unit Testing a class with ServiceLocatorFactoryBean Autowired

I have a Interface which is registered as part of ServiceLocatorFactoryBean. The main purpose of this Interface is to act as a factory.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.html
I have "autowired" this Interface in various classes, that I want to test now with Mockito.
The issue is Mockito doesn't support interfaces. How can inject a mock of this interface in the class I am testing.
The only alternative I see is to run the test using SpringJunitRunner and providing an Application Context which has the bean configurations. But this is too verbose.
I take it you'd like to spy on the implementation that Spring generated for your interface?! That's close to impossible to achieve with what you have so far... However there are at least the following alternatives below.
Suppose we have the following setup:
public interface MyService {
String doIt();
}
#Component
public static class ServiceConsumer {
#Autowired
private MyService service;
public String execute() {
return service.doIt();
}
}
0) Later edit: while roaming around, I found that it may be possible to spy and even replace an autowired field with a mock, and fairly easy too, using Springockito-annotations.
#RunWith(SpringJUnit4ClassRunner.class)
#ComponentScan
#ContextConfiguration(loader = SpringockitoAnnotatedContextLoader.class, classes = {SpringockitoConsumerTest.class})
public class SpringockitoConsumerTest {
#WrapWithSpy(beanName = "myService")
#Autowired
private MyService mockService;
#Autowired
private ServiceConsumer consumer;
#Test
public void shouldConsumeService() {
assertEquals("allDone", consumer.execute());
verify(mockService).doIt();
}
}
If Springockito-annotations is out of the question, please see the 2 original suggestions below
1) You could just create your mock of the interface and auto-inject it Mockito in your bean. This is the simplest solution (I could think of at the time of writing) but it does not ensure that the #Autowired annotation was not forgotten in the consumer (perhaps a dedicated test could be added?!):
public class AutoInjectMocksConsumerTest {
#Mock
private MyService serviceMock;
#InjectMocks
private ServiceConsumer consumer = new ServiceConsumer();
#Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
when(serviceMock.doIt()).thenReturn("allDone");
}
#Test
public void shouldConsumeService() {
assertEquals("allDone", consumer.execute());
verify(serviceMock).doIt();
}
}
2) Alternatively as you also said, you could run it with the SpringJunitRunner making a minimum of effort to define and instantiate the necessary Spring context while also providing your own service mock. Albeit people may complain this solution is not that clean, I find it sufficiently elegant and it also validates that the #Autowired annotation was not forgotten in the consumer implementation.
#RunWith(SpringJUnit4ClassRunner.class)
#Configuration
#ComponentScan
#ContextConfiguration(classes = {SpringAutowiringConsumerTest.class})
public class SpringAutowiringConsumerTest {
#Autowired
private MyService mockService;
#Autowired
private ServiceConsumer consumer;
#Test
public void shouldConsumeService() {
assertEquals("allDone", consumer.execute());
verify(mockService).doIt();
}
#Bean
public MyService mockService() {
MyService serviceMock = mock(MyService.class);
when(serviceMock.doIt()).thenReturn("allDone");
return serviceMock;
}
}

ContainerRequestFilter + #Autowired + Null for DAO

I am implementing the Basic auth for RestEasy API. I tried to implement javax.ws.rs.container.ContainerRequestFilter with annotation #Provider. Everything looks clean until i tried #Autowired my DAO class in my implementation class. Initially, i hard coded my Username & Password in the implemented class and it works. Finally, i started integrating with my DAO class to get those values from DB. But #Autowired annotation is returning null for my DAO. I tried googling and tried lot of option, but still i am getting null for that DAO.
I have annotated my DAO class with #Repository.
#Provider
public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
#Autowired
private SecurityDao securityDao;
...
#Repository("securityDao")
public class SecurityDaoImpl implements SecurityDao {
Can someone help me in this issue?
Thanks in advance!
Edit -
#ApplicationPath("/")
public class RestApplication extends Application{
#Override
public Set<Object> getSingletons()
{
Set<Object> singletons = new HashSet<Object>();
singletons.add(new SecurityInterceptor());
return singletons;
}
}
I think i see same issue in this post also.Spring autowired dao is null. Did anyone have solution for this issue? Please let me know. Thanks

Could not autowire field when bean implements some interface with Spring

I am using Spring in my Java Application, all the #Autowired annotations working until now.
Simplified example would be:
#Component
public class MyBean implements MyInterface {
...
}
#Component
public class MyOtherBean {
#Autowired
private MyBean myBean;
...
}
Once I try to start the Application, I get:
java.lang.IllegalArgumentException: Can not set MyBean field MyOtherBean.myBean to $ProxyXX
The interface contains just two public simple methods and the class implements them.
Both classes are public and have public default constructor. (I even tried to instantiate them in tests.
Once I remove the implements section, everything works correctly.
What can be wrong with the implementation of the interface? What is $ProxyXX?
I suspect the issue is that Spring is injecting an AOP proxy which implements MyInterface - possibly for the purposes of transaction management or caching. Are any of MyBean's methods annotated #Transactional or annotated with any other annotation?
Ideally you'd probably want to reference MyBean by it's interface type - which should resolve the issue.
#Component
public class MyOtherBean {
#Autowired
private MyInterface myBean;
...
}
If you have more than one bean implementing MyInterface then you an always qualify your bean by name.
#Component
public class MyOtherBean {
#Autowired
#Qualifier("myBean")
private MyInterface myBean;
...
}
By default, Spring uses Java dynamic proxies to implement AOP when the bean implements an interface. The easiest and cleanest way to solve your problem is to make program on interfaces, and inject theinterface insted of the concrete class:
#Component
public class MyOtherBean {
#Autowired
private MyInterface myBean;
...
}
See http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/htmlsingle/#aop-proxying for how to force Spring to always use CGLib.

How Spring injection works for subclass

A question on how Spring injection works? If I inject same service in a class and all its sub-classes is it going to to inefficient? How does Spring's container going to store/control this?
public class baseClass {
#Autowired
private iService serviceName
}
public class extendedClassA extends baseClass {
#Autowired
private iService serviceName
}
public class extendedClassB extends extendedClassA {
#Autowired
private iService serviceName
}
Thanks..
I haven't tried but I believe it is going to cause problem.
The main problem is not due to Spring, but variable shadowing in your example. BaseClass' serviceName is shadowed by child class, that means, if you haven't done special handling, BaseClass' serviceName is going to be null.
You may want to consider doing this:
// !!!! Mind your naming convention!!!!!!
public class BaseClass {
#Autowired
private FooService fooService;
protected FooService getFooService() {
return this.fooService;
}
public setFooService(FooService fooService) { ... }
}
public class ExtendedClassA extends BaseClass {
// no need to inject fooService again, whenever it need to use that,
// simply do getFooService() and use it
}
Adrian Shum response seems fine but you need to declare too your BaseClass bean in your applicationContext file with the property "abstract=true"
<bean id="baseClass" class="BaseClass" abstract="true"/>

Resources