Null pointer exception for Autowired object in Spring - java

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)

Related

Dependencies does not inject during weblogic deployment

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

JAX-WS web service : Beans not injected : NullPointerException

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;
....

Spring controller not created

There is a small Struts application and I am trying to enable Spring-mvc on it. It's already using Spring to handle the DB transactions. I have two questions:
Component scan will not pick up my controllers if I try to add a new base package.
If I place my controllers in an existing base package, I can see them created in Spring application context. But then the request mapping still does not work.
Here are my relevant code snippets:
web.xml:
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>*.site</url-pattern>
</servlet-mapping>
Here is springDispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<mvc:annotation-driven />
<context:component-scan base-package="com.mycom.eps.test, com.mycom.epsadmin"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="exceptionHandler" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">error</prop>
<prop key="org.hibernate.exception.GenericJDBCException">jdbcerror</prop>
</props>
</property>
</bean>
</beans>
Here's part of ApplicationContext.xml:
<context:annotation-config />
<context:component-scan base-package="com.mycom.eps, com.mycom.tiff" />
<tx:annotation-driven proxy-target-class="true" />
I've got two Controllers:
package com.mycom.eps.test;
// import statements
#Controller
public class TestController {
#RequestMapping(value="/test", method={RequestMethod.GET, RequestMethod.POST})
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws EpsException {
Map<String, Object> modelMap = new HashMap<String, Object>();
return new ModelAndView("/details", modelMap);
}
}
Another controller:
//This is a new package I am trying to create
package com.mycom.epsadmin.controller;
// import statements
#Controller
public class PackageController {
#RequestMapping(value="/sendPackage", method={RequestMethod.GET, RequestMethod.POST})
public ModelAndView sendPackage(HttpServletRequest request, HttpServletResponse response) throws EpsException {
Map<String, Object> modelMap = new HashMap<String, Object>();
return new ModelAndView("/details", modelMap);
}
}
My first question is, why is the com.mycom.epsadmin.controller.PackageController never created in web application context (I inspected the spring log and couldn't find it)?
While trying to figure out about my first question, I created another controller com.mycom.eps.test.TestController (hence the name of the controller). While this one does get created in the Web application context, the request is never intercepted (404 error).
Here's how I am trying to call it:
$.ajax({
type: "POST",
url: "test.site",
cache: false
});
When I try to go to the page through browser http://http://localhost:8080/mycom/test.site, I am getting 404 error as well.
Sorry for the lengthy post! But can someone kindly point me in the right direction? Thanks a bunch!
UPDATE:
Just found out that the test controller is actually picking up the request (really sorry about that)! So my second question is moot.
Try after adding com.mycom.epsadmin in the ApplicationContext
<context:component-scan base-package="com.mycom.epsadmin, com.mycom.eps, com.mycom.tiff" />

Spring Framework Project not loading?

I have been working with the Spring framework for a few days trying to set up a project, based off of something like this tutorial.
Unfortunately, when i deploy the project using Tomcat, I get a screen that looks something like this:
I'm not really sure to go from here. I've checked the web.xml and any other relevant .xml files that would maybe affect the error, but I can't see an error. Below I will post my web.xml and spring-config.xml files.
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>Campaign Spring V2</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring_config.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:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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-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.bridge.campaignspring.controller" />
<context:property-placeholder location="classpath:application.properties" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.bridge.campaignspring.Campaign</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="CampaignDao" class="com.bridge.campaignspring.dao.CampaignDAOImpl" />
<bean id="CampaignService" class="com.bridge.campaignspring.service.CampaignServiceImpl" />
</beans>
If need be, I can post the project to GitHub to see if there is an even larger flaw that could be found in the code. Also, if any other parts of the project need to be posted I will update the OP to display anything. Thanks!
EDIT: http://localhost/ does not load either, I was incorrect with my previous statement.
EDIT2: Here is a link to the project on GitHub.
EDIT3: After going through the Spring tutorial again this was resolved!
You didn't follow the tutorial well. The controller mapping starts with
#RequestMapping("/")
public class AppController {
The first annotation #RequestMapping("/") is important for spring to calculate the path used by the request.
And this code is missing
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.bridge.compaignspring.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
Without it Spring cannot autowire properties that depend on sessionFactory.
Just done a quick check through the github project, you have more problems that I thought.
You are using XML config to create the DispatchServer with the config at Spring-config.xml, while also having a AppInitializer on the class path.
The AppInitializer uses AppConfig which creates a Datasource bean, your XML also creates a Datasource bean and also a SessionFactory.
Tomcat will find the AppInitializer and is running through that first.
This means it tries to autowire the SessionFactory before the one in the XML have been created.
To move your code off this problem do the following things.
move spring_config.xml from /webapp/WEB-INF to /resources
add the following #import line to AppConfig.java
#Configuration
#EnableWebMvc
#ImportResource("classpath:spring-config.xml")
#ComponentScan(basePackages = "com.bridge.campaignspring")
public class AppConfig {
Now you need to remove 1 of the 2 DataSource beans you are creating. I would suggest removing the one in the XML as that is using invalid property values. i.e. ${database.driver} does not exist.
After you have made those changes, you will still have other problems, but you are further along than you were.
did u set Web Module Path in tomcat settings ?
refer these question Unable to run Spring REST application using Tomcat

Weird Spring Context Component Scan

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" />

Categories