I want to deploy my project on weblogic but when I deploy the war, my spring applicationContext gets loaded and when it starts hydrating my caches it crashes giving me a null pointer exception. When I debugged I saw that my persistence entity class, that is used during the method, is instantiated with out its dependencies meaning they did not get injected.
My entity class is marked with #Configurable and the getter and setter methods for the dependencies are marked with #Transient. Also, when I run my tests it does inject the dependencies in the entity class and it seems it does not inject when I am trying to deploy to weblogic. I have no idea where to start looking for the problem thus I have no idea which code I should supply you with.
Any tips on what I should google or where to look into would be much appreciated. Also if you want to have a look at some code just ask and I will add it.
Thank you and I apologize for the lack of code but I have no idea which bit would actually help and which code would be useless.
EDIT:
Adding code
Entity class
#Configurable
#javax.persistence.Entity
#Table(name = "Some_Table")
public class InteractionImpl implements Interaction, Serializable {
private Long interactionId;
private Long initiatorEntityNr;
private Long agentEntityNr;
transient private BuilderB builderB;
transient private BuilderA builderA;
#Id
#Column(name = "justAnotherID")
public Long getInteractionId() {
return interactionId;
}
public void setInteractionId(Long interactionId) {
this.interactionId = interactionId;
}
#Column(name = "someCodeB")
private Long getInitiatorEntityNr() {
return initiatorEntityNr;
}
private void setInitiatorEntityNr(Long initiatorEntityNr) {
this.initiatorEntityNr = initiatorEntityNr;
}
#Column(name = "someCodeA")
private Long getAgentEntityNr() {
return agentEntityNr;
}
private void setAgentEntityNr(Long agentEntityNr) {
this.agentEntityNr = agentEntityNr;
}
#Transient
public Agent getAgent() throws CrmEntityCreationException {
if (getAgentEntityNr() != null)
return builderA.buildShallowEntity(getAgentEntityNr());
else
throw new CrmEntityCreationException("There was no agent entity number so the entity could not be found");
}
#Transient
public void setAgent(Agent agentEntity) {
setAgentEntityNr(agentEntity.getEntityNumber());
}
#Transient
public Customer getInitiator() throws CrmEntityCreationException {
if (getInitiatorEntityNr() != null) {
return builderB.buildShallowEntity(getInitiatorEntityNr());
} else {
throw new CrmEntityCreationException("The interaction does not contain an initiator entity number");
}
}
#Transient
public void setInitiator(Customer initiatorEntity) {
setInitiatorEntityNr(initiatorEntity.getEntityNumber());
}
#Transient
private BuilderB getCustomerBuilder() {
return builderB;
}
#Inject
#Transient
public void BuilderB(BuilderB builderB) {
this.builderB = builderB;
}
#Transient
private BuilderA getBuilderA() {
return builderA;
}
#Inject
#Transient
public void setBuilderA(BuilderA builderA) {
this.builderA = builderA;
}
}
Application 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:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>
<context:component-scan base-package="crm.persistence"/>
<context:component-scan base-package="crm.services.impl"/>
<context:annotation-config/>
<context:spring-configured/>
<bean id="hazelcast" class="com.hazelcast.core.Hazelcast" factory-method="newHazelcastInstance"/>
<bean id="httpComponentMessageSender" class="org.springframework.ws.transport.http.HttpComponentsMessageSender"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#someConnection:1521:xe"/>
<property name="username" value="someUsername"/>
<property name="password" value="somePassword"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="loadTimeWeaver" ref="loadTimeWeaver"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<bean class="org.springframework.transaction.aspectj.JtaAnnotationTransactionAspect" factory-method="aspectOf">
</bean>
<bean id="interactionCache" class="crm.services.impl.Caching.InteractionCacheImpl">
<property name="ammountOfInteractionToReturn" value="10"/>
</bean>
<bean id="interactions" class="crm.persistence.entities.InteractionImpl" scope="prototype"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="interactionCache"/>
<property name="targetMethod" value="rehydrateAllCaches"/>
</bean>
<bean id="agentCache" class="crm.services.impl.Caching.AgentCacheImpl"/>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="agentCache"/>
<property name="targetMethod" value="rehydrateAll"/>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="alertCache"/>
<property name="targetMethod" value="rehydrateAll"/>
</bean>
</beans>
Then my spring webservice servlet
<?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:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:applicationContext.xml"/>
<!--scans for spring-ws annotation-->
<sws:annotation-driven/>
</beans>
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
and then my weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd">
<context-root>/CrmService</context-root>
<container-descriptor>
<prefer-application-packages>
<package-name>org.jboss.logging.*</package-name>
</prefer-application-packages>
</container-descriptor>
</weblogic-web-app>
As seen in my application context I have two caches that I rehydrate. The hydrate method calls a DAO to find a list of relevant interactions (Entity class) and then calls the getAgent() and getInitiator() methods. Since builderA and builderB does not get injected it throws a null pointer exception.
Just to remind you that it injects these classes in my integration tests but not when I try and deploy it to weblogic. I don't use tomcat
Related
I'm building a new project for SOAP web services. Earlier I was using JDBC layer for opening and closing connections. Now, I'm converting it into Spring with JDBC template. I've configured all the layers and annotated the components. When I try to use the dao bean in my service impl class, it throws me null pointer exceptions
#Service
#WebService
public interface Transaction { // Web methods here for SOAP Web service
}
Impl class
#Component
#WebService
public class TransactionImpl implements Transaction{
#Autowired
BBDao dao; --> This is coming as null when I use it in the method
}
BBDao interface is as follows
public interface BBDao { /* Methods in it */ }
The implementation class which is implementing BBDao interface is
public class BBDaoImpl extends JdbcDaoSupport implements BBDao {
#Autowired
ServletContext ctx;
#Autowired
DataSource dataSource;
// Methods overriding here
}
Servlet defined in web.xml
<servlet>
<servlet-name>spring-web</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-web</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And finally the spring-web-servlet.xml is
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.bb.controller,com.bb.dao,com.bb.service" />
<context:property-placeholder location="classpath:datasource-cfg.properties" />
<bean id="bbDAO" class="net.bb.dao.BBDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- AS400 Data source Bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.ibm.as400.access.AS400JDBCDriver" />
<property name="url" value="${as400.url}" />
<property name="username" value="${as400.username}" />
<property name="password" value="${as400.password}" />
</bean>
<mvc:annotation-driven />
</beans>
The BBDao bean object is coming as null.
Is there any mistake in my configuration? Any advice would be greatly appreciated.
P.S : I have followed other posts as well, as most of the posts talk about component scan only and the packages are correct
We cant autowire an interface without Implementation as we cant create instance for interface. But you can try the ones below and see if it works.
Few things what you could do.
Add to your spring-webservlet.xml
And also refer this
user annotation like #ConditionalOnMissingBean(BBDao.class)
I have developed a JAX-WS based web-service. I have Web service layer, service layer and a Dao layer. When i call a service method from web service class it gives null pointer exception. The reason is the service class bean is not getting injected.
web-service class:
package com.test.webservice.controller;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.test.salary.service.SalaryService;
#WebService
public class EmployeeSalaryWebService {
private SalaryService salaryService;
/**
* #param salaryService the salaryService to set
*/
#WebMethod(exclude = true)
public void setSalaryService(SalaryService salaryService) {
this.salaryService = salaryService;
}
#WebMethod
public double getEmployeeSalary(String name){
System.out.println("==== Inside getEmployee Salary === "+salaryService );
return salaryService.calculateSalary(name);
}
}
Application-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="salaryWebService"
class="com.test.webservice.controller.EmployeeSalaryWebService">
<property name="salaryService" ref="salaryService" />
</bean>
<bean name="salaryService" class="com.test.salary.service.SalaryServiceImpl">
<property name="salaryDAO" ref="salaryDAO" />
</bean>
<bean name="salaryDAO" class="com.test.salary.dao.SalaryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="LOCAL" />
<property name="password" value="abcdef" />
</bean>
</beans>
web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/salaryConfiguration.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Please let me know why the SalaryService salaryService not getting injected.
Your service class and bean in context is two separate things. I believe that you don't get bean from context and just use class, aren't you?
I advice you marking your service class with
#Component
That will make your class to become spring bean.
Then you can use inside following annotation.
#Autowired
This will try to find appropriate bean with annotated element type in spring context.
And don't forget to put into your context.
<context:component-scan base-package="..." />
This will search all classes marked as #Component and add it to spring context as beans.
For more detailed instruction you can check this article
https://www.javacodegeeks.com/2010/11/jaxws-with-spring-and-maven-tutorial.html
Make your SalaryService auto wired as follows:
public class EmployeeSalaryWebService {
#Autowired
private SalaryService salaryService;
....
I have #Component, A, which AutoWires a class which contains simple configurations for class A. I've created a bin for configuration file. But for some reason it comes as null. Could you please help me to find out the problem?
#Component
public class SearchEngineDriver {
#Autowired(required = true)
private EngineContext context;
public SearchEngineDriver(){
String clusterName = context.getClusterName();
}
}
public class EngineContext {
private String clusterName;
public EngineContext(String clusterName){
this.clusterName = clusterName;
}
public String getClusterName(){
return this.clusterName;
}
}
3rd class.
#Autowired
private SearchEngineDriver searchEngineDriver;
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.electronsoftware" />
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<import resource="classpath*:/application-context.xml"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
application-context.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"
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-3.2.xsd">
<context:property-placeholder location="classpath:application.properties"/>
<bean id="searchEngineContext" class="org.electronsoftware.KGB.search.context.EngineContext" >
<constructor-arg value="${kgb.search.engine.clustername}"/>
</bean>
</beans>
You are accessing the autowired field from the constructor. At the time the constructor runs, Spring has not yet got the chance to initialize the field. Instead use a #PostConstruct method to perform logic which depends on the autowired value.
I found many solutions to lots of my queries already from stackoverflow and this is first time I am asking a question here and I don't really know what's wrong with that. Actually I am trying to Autowire one of my classes by type but unable to do that. Following is the source code in sequence.
Spring Context
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/mysqlConfig.properties" />
<bean id="sessionManager" class="com.bakaenterprise.dal.SessionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:annotation-config />
<context:component-scan base-package="com.bakaenterprise" />
<bean id="searchManager" class="com.bakaenterprise.bl.SearchManager" />
<bean id="fileDao" class="com.bakaenterprise.dal.impl.FileUploadDao" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="10" />
<property name="maxActive" value="5" />
<property name="maxWait" value="5000" />
</bean>
<!-- Hibernate Configuration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource" p:packagesToScan="com.bakaenterprise.beans">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
<prop key="hibernate.generate_statistics">
true
</prop>
</props>
</property>
</bean>
</beans>
interface
package com.bakaenterprise.dal;
import com.bakaenterprise.beans.FileUploadBean;
import com.bakaenterprise.core.base.GenericDao;
public interface IFileUploadDao extends GenericDao<FileUploadBean> {
}
implementation
package com.bakaenterprise.dal.impl;
import com.bakaenterprise.beans.FileUploadBean;
import com.bakaenterprise.core.base.HibernateDaoSupport;
import com.bakaenterprise.dal.IFileUploadDao;
import java.io.Serializable;
import java.util.List;
import org.springframework.stereotype.Component;
/**
* #author ali
*/
#Component
public class FileUploadDao extends HibernateDaoSupport<FileUploadBean> implements IFileUploadDao {
#Override
public boolean save(FileUploadBean obj) {
super.save(obj);
return true;
}
#Override
public FileUploadBean getRecordById(Serializable id) {
return super.getRecordById(id);
}
public boolean deleteRecordById(int id){
return super.deleteById(id);
}
#Override
public List<FileUploadBean> listAll() {
return super.listAll();
}
}
Manager class
package com.bakaenterprise.bl;
package com.bakaenterprise.bl;
import com.bakaenterprise.dal.IFileUploadDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* #author ali
*/
#Component
public class TestManagerImpl implements ITestManager {
#Autowired
private IFileUploadDao fileDao;
#Override
public void test() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public IFileUploadDao getFileDao() {
return fileDao;
}
#Override
public void setFileDao(IFileUploadDao fileDao) {
this.fileDao = fileDao;
}
}
Code where I am using Search Manager and testing FileUploadDao object is null or not
#Autowired
private ITestManager testManager;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
IFileUploadDao fileUploadDao = testManager.getFileDao();
// now testManager is null
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>SearchServlet</servlet-name>
<servlet-class>com.bakaenterprise.server.SearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SearchServlet</servlet-name>
<url-pattern>/servlets/SearchServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/jstl/core_rt</taglib-uri>
<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/jstl/xml_rt</taglib-uri>
<taglib-location>/WEB-INF/tld/x_rt.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/jstl/fn_rt</taglib-uri>
<taglib-location>/WEB-INF/tld/fn.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/jstl/fmt_rt</taglib-uri>
<taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
</taglib>
</jsp-config>
<filter>
<filter-name>performance</filter-name>
<filter-class>com.bakaenterprise.util.PerformanceLog</filter-class>
</filter>
<filter-mapping>
<filter-name>performance</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Now File Dao is always null, I think its not scanning the components though base package is correct. Any help or suggestion would be highly regarded and appreciated. And I know this type of question is being asked many times so apologizes for asking it again, those answer didn't work for me.
I believe you have to declare this explicitly in applicationContext for the bean you want to autowire.
<bean id="searchManager" class="com.bakaenterprise.bl.SearchManager" autowire="byType"/>
An alternative is to autowire byName, which should work in your case too (since member variablefileDao has the same name as the bean ID fileDao).
SearchManager should be annotated also for the IFileUploadDao implementation bean to be injected during the component scan
#Component
public class SearchManager {
Also you're initializing SearchManager manually which will result in its dependencies not being injected - The bean needs to be managed by Spring. As there is no direct way to inject Spring Beans into a Java Servlet, you can use a Spring framework HttpRequestHandler.
public class AnnotatedHttpServletRequestHandler implements HttpRequestHandler {
#Autowired
private SearchManager searchManager;
...
}
Specific details are described in Injecting Spring Beans into Java Servlets
Try to add depends-on attribute in your spring context configuration:
<bean id="searchManager" class="com.bakaenterprise.bl.SearchManager"
depends-on="fileDao" />
EDIT:
You FileUploadDao defined twice, one bean with #Component annotation and second with XML:
<bean id="fileDao" class="com.bakaenterprise.dal.impl.FileUploadDao" />
So, you just create two copies of one bean! And it's a problem I think.
EDIT-2
Try to remove this XML definitions:
<bean id="searchManager" class="com.bakaenterprise.bl.SearchManager" />
<bean id="fileDao" class="com.bakaenterprise.dal.impl.FileUploadDao" />
and add #Component annotation to SearchManager
EDIT-3
You need to autowire SearchManager:
public SearchServlet extends HttpServlet {
#Autowired
private SearchManager searchManager;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
You have some options here, you can annotate your class SearchManager with:
#Component
#Configurable - The #Configurable is used to mark a class eligible for Spring dependency injection. It's should be used when you can't or have no intention to use your class as a Spring Bean (Available since Spring 2.0)
There are other ways to wire your classes, but you may lose some benefits.
You also should remove the xml declaration:
<bean id="searchManager" class="com.bakaenterprise.bl.SearchManager" />
My goal is to instanciate the EntityManagerFactory from applicationContext.xml file to get all posts registered in SQL database.
Here's the content of the main files :
applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Properties files linkers -->
<context:property-placeholder location="/WEB-INF/resources/database/jdbc.properties"/>
<context:property-placeholder location="/WEB-INF/resources/database/hibernate.properties"/>
<!-- Config database - initialization -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Three main layers definition -->
<context:annotation-config />
<context:component-scan base-package="com.zone42"/>
<!-- Transaction sub-system initialization -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
(WEB-INF/classes/)persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="post-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.zone42.model.Post</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
PostDAO.java
public class PostDAO extends GenericDAOEntity<Post> implements IPostDAO
{
}
GenericDAOEntity.java
#Transactional
public class GenericDAOEntity<T> implements IGenericDAO<T>
{
/**
* Properties
*/
#Autowired
#PersistenceContext(unitName="post-unit")
private EntityManagerFactory entityManagerFactory/* = Persistence.createEntityManagerFactory(persistence_unit_name)*/;
//Get all posts
#SuppressWarnings("unchecked")
public List<T> findAll(Class<T> obj) {
EntityManager entityManager = this.entityManagerFactory.createEntityManager();
Query query = entityManager.createQuery("from " + obj.getSimpleName());
return (query.getResultList());
}
/**
* Accessors
*/
public EntityManagerFactory getEntityManagerFactory() {
return entityManagerFactory;
}
#PersistenceContext(unitName="post-unit")
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
}
I tried several config combinations but without success. The NullPointerException comes from the findAll method when I want to create an instance of EntityManager from the entityfactory instance. I think I have a configuration problem. I want to precise that the code works whn I instanciate the EntityManagerFactory using operator new directly in the class. Now I just want to allocate my factory choosing another way, the one using xml from appicationContext.xml file. Can anyone help me? Thanks in advance.
You need to either mark the field/setter as #Autowired or explicitly wire the reference up in your XML:
<bean class="PostDAO">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>