Spring's #Autowired doesn't inject dependency - spring

I have a project that consists of various modules.
Basically, I've worked with Spring MVC & JUnit 4, and everything was working good.
But Now, I added few classes which aren't related to testing or MVC, and the #Autowired annotation doesn't inject objects to them.
The same objects are injected to the MVC and JUnit classes, so I realy confused.
This is the Spring Context XML:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scan base-package="com.justic.more" />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="monkDAO" class="com.justic.more.data.monkDAO" />
<bean id="BidDAO" class="com.justic.more.data.BidDAO" />
</beans>
The Class that I want to inject to:
#Component
Public Class Tesser {
#Autowired
MonkDAO monkdao;
...
blablabla
...
}

From the chat with OP it became clear that he created the object like Tesser tesser = new Tesser() instead of injecting it into the test class.
Spring has no chance to autowire dependencies in beans that it does not create itself.
The solution is to autowire the Tesser object into the test class so Spring can inject the dependencies.
#Autowired
private Tesser tesser;
#Test
public void testSth() {
assertTrue(tesser.someBoolReturningMethodUtilizingMonkDAO());
}

Add qualifiers:
#Resource(name = "monkDAO")
If you start with annotations, go all the way.

Related

Spring AOP Pointcut not called

i work with JSF 2.2 + Spring framework 3.2.4
So, i have this applicationContent.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<aop:aspectj-autoproxy proxy-target-class="true" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com.vulcan.controller" />
<context:component-scan base-package="com.vulcan.service" />
<context:component-scan base-package="com.vulcan.dao" />
<context:component-scan base-package="com.vulcan.spring.aop" />
.....
Then i have aspect component
in
package com.vulcan.spring.aop;
#Aspect
public class LoggingService {
private Log log = LogFactory.getLog(this.getClass());
#Pointcut("execution(* *.*(..))")
protected void loggingOperation() {}
#Before("loggingOperation()")
public void logJoinPoint()
{
System.out.println ("Hello");
}
....
With this type of execution i assume this pointcut will be triggered on every methods. But the problem is, this pointcut isn't triggered ? Any idea why ? Thanks
FYI, i using glassfish 4, and when i deploy my web app i didn't receive any error configuration. So i assume my configuration is fine.
#Aspect annotate classes aren't automatically detected by Spring and because it isn't detected it isn't known to the <aop:aspectj-autoproxy /> beans. So basically there is no aspect.
Either add #Component to your #Aspect annotated class(es) so that Spring can detect and use the aspect.
#Compopnent
#Aspect
public class LoggingService { ... }
or declare the aspect explictly in your xml file
<bean class="LoggingService" />
Either way the aspect will be picked up by the <aop:aspectj-autoproxy /> beans and the advice will be run.
Try using execution(* *(..)).

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.

contex:componet-scan not picking up beans defined in jar file

I am working on a Spring Project:Common that uses a combination of Annotaions and Spring IOC in XML.
I have a common.jar which contains Common classes used by various projects.
And I have another Spring Project:WebService that refers to the beans defined in common.jar.
For some reason beans marked with #Component Annotation in Common.jar are not being picked up by my WebService Project. But all beans defined using <bean id="" class="" /> in Common.jar were picked up.
Below are the code for all files that have necessary configuration. Would really appreciate your help. Thanks in advance.
In Common.jar, applicationContext.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<import resource="springConfig/app/AppServices.xml"/> <!-- Beans in this file were loaded. -->
<context:annotation-config/>
<context:component-scan base-package="com.ipd.app1"/> <!-- Beans for all classes under app1 package were NOT loaded -->
</beans>
In Common.jar, AppServices.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="inquireOrderApp" class="com.ipd.app.inquireOrderDetail.InquireOrderDetailAppImpl"/>
</beans>
Common.jar, com.test.app.MyClass
package com.ipd.app1;
#Component("createOrderApp")
public class CreateOrderAppImpl implements CreateOrderApp {
#Override
public CreateOrderResponse processMSSOrder(TransactionContext tx,
CreateOrderRequest createOrderRequest)
throws ApplicationException, Exception {
System.out.println("In App Layer Class CreateOrderAppImpl to ProcessOrder.");
return response;
}
}
WebService Project, IpdService_IPDSoapHTTPPortImpl.java
#WebService(portName = "IpdSoapHTTPPort", serviceName = "IpdService", targetNamespace = "http://ipd.com/ipdIpdweb/", wsdlLocation = "/wsdls/Ipd.wsdl", endpointInterface = "com.ipd.ipdIpdweb.IpdPortType")
#BindingType("http://schemas.xmlsoap.org/wsdl/soap/http")
public class IpdService_IpdSoapHTTPPortImpl implements IpdPortType {
ApplicationContext ctx;
public IpdService_IpdSoapHTTPPortImpl() {
this.ctx = AppContext.getCtx();
}
#Override
public void createOrder(WSHeader wsHeader,
CreateOrderRequest createOrderRequest,
Holder<WSResponseHeader> wsResponseHeader,
Holder<CreateOrderResponse> createOrderResponse)
throws WSException {
CreateOrderApp createOrderApp = (CreateOrderApp) ctx.getBean("createOrderApp");
res = createOrderApp.processOrder(tx, createOrderRequest);
res.setResponseCode(BigInteger.valueOf(0));
res.setResponseMessage("Success");
.....
}
}
Please let me know if you need see the code for any other file.
Well add this to applicationContext.xml
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

Spring bean not injected into CXF web service, Why?

I am writing a RESTful service (using CXF on JBoss) in which I have inject another class using Spring (Autowired). But the class is not getting injected and is null.
Web Service Interface and Class (Where injection needs to happen)
package com.company.project.web;
#Path("/myws")
public interface IMyWebService {
#POST
#Path("/doSomething")
#Consumes("application/json")
#Produces("application/json")
MyResponse doSomething(MyRequest myRequest)
}
#Service("myWebService")
public class MyWebService implements IMyWebService {
#Autowired
private IMyCore myCore;
public MyResponse doSomething(MyRequest myRequest) {
....
}
}
That which has to be injected
package com.company.project.biz;
public interface IMyCore {
MyResponse doSomething(MyRequest myRequest);
}
#Component("myCore")
public class MyCore implements IMyCore {
public MyResponse doSomething(MyRequest myRequest) {
.....
}
}
Beans.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:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<context:annotation-config />
<context:component-scan base-package="com.company.project"/>
<jaxrs:server id="myWebService" address="/">
<jaxrs:serviceBeans>
<bean class="com.company.project.web.MyWebService" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="json" value="application/json" />
</jaxrs:extensionMappings>
</jaxrs:server>
</beans>
My service is active (http://localhost:8080/{warname}/myws/doSomething) but the MyCore instance is not being injected into MyWebService (in the myCore field). It is always null and my service does not work as expected, instead throws NullPointerException
Tried all inputs gathered over google. No luck! Your help is highly appreciated.
Regards
Try to add below method to your web service:
#PostConstruct
public void init() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
The current web application context (usually the one loaded by ContextLoaderListener) will be used for autowiring, so the IMyCore bean has to be defined in the context listener configuration file and not in the web service one.
If you want to use Spring Beans in CXF Web Service class, then declare WebService as following in the XML configuration file of the CXF (e.g. spring-cxf.xml)
<bean id="hello" class="demo.spring.service.HelloWorldImpl" />
<jaxws:endpoint id="helloWorld" implementor="#hello" address="/HelloWorld" />
Declare separated bean for the WebService class and then put it in the endpoint with an ID. Like this you will have spring managed bean, where you can use AutoWired annotations as well.
Your beans never won't be injected automatically if you will declare your web service as following.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld"/>
In this case you will need either:
Inject spring beans manually
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
Or retrieve the beans one by one from the spring context
ApplicationContext context = ...; // your Spring ApplicationContext
HelloBean helloBean = (HelloBean) context.getBean("bean");
I haven't tried this for JAX-RS, but the approach in my opinion should be the same.
From CXF official documentation.
Try to add below bean configuration at Beans.xml
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
In my case, it worked..

How to initialized java bean with annotation in spring framework?

I have a Java bean:
public class User{
private Integer userid;
private String username;
private String password;
private boolean enable;
//getter and setter
}
I am able to initialize it as a spring bean at context.xml via:
<context:component-scan base-package="com.myCompany.myProject" />
But I don't want initialize it in xml. How can I initialize it with sring 3 annotation. I tried with the following:
#Component
public class User{
private Integer userid;
private String username;
private String password;
private boolean enable;
//getter and setter
}
But the above did not work for me. Any ideas?
I believe that is because you have enable component scan on the package com.myCompany.myProject and not on the package com.myCompany.myProject.db
Change your scan definition to this : <context:component-scan base-package="com.myCompany.myProject.db" /> (or add a new one, if you want classes from the other package as well) and you can remove the bean definition from XML and have your annotation work for you.
Silly, but still, ensure that the #Component annotation is that of Spring's. I've at times faced this silly issue of defining an annotation that is actually not from the desired library (owing to the same name of the annotation, by different libraries in my classpath).
You need to add
<context:annotation-config />
With this XML my Autowiring works flawless:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.vanilla.example"></context:component-scan>
</beans>
you shouldn't need to have both declared.
Use of context:annotation-config allows for autowiring of beans via annotations etc
Use of context:component-scan provides everything that context:annotation-config, but allows for autodiscovery of beans. The package you supply in context:component-scan will scan that package plus all sub packages.
Hope this helps
Be sure that the "User" class is the package or sub-package of the
"com.myCompany.myProject".
You do NOT need to include <context: annotation-config/>, it is
included with component-scan.
The bean is available with the name "user" by default, unless you
specify the bean name with #Component("myBeanName")
Once that is done, you can autowire the bean into another with:
#Autowired
User user;
OR
#Inject
User user;
NOTES:
#Inject is a javax.inject annotation the injection is NOT required.
#Autowired is a Spring annotation and the injection is required.
#Autowired can be used in one of the following ways:
just above the member variable
constructor that accepts a User bean
setter that accepts a User bean.
I have configured my xml file in this way , this will help you to solve the problem.
For Context-componentscan use
<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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.java.Controllers"></context:component-scan>
<context:component-scan base-package="com.java.dao"></context:component-scan>
<context:component-scan base-package="com.java.bean"></context:component-scan>
Or else u can use
<context:component-scan base-package="com.java.*"></context:component-scan>
next for annotation driven use
<mvc:annotation-driven />
For resources use this
<mvc:resources location="/" mapping="/**"/>

Resources