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;
....
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)
like in topic, but if I will do just persistence.xml file in META-INF with unitName, and do that by this, then everything is good, and my sql query is working, and connection is open.
Here is my view of my project:
project structure
Here is code where I invoke method, my HomeController.java:
#Controller
#RequestMapping("/")
#SessionAttributes("/")
public class HomeController {
#Autowired
private UserDao userDao;
#Autowired
private EmployeeDAO employeeDao;
#RequestMapping(value = {"/dam"}, method = RequestMethod.GET)
public String setupForm(Model model)
{
userDao.getUserByUserId("2");
//employeeDao.getAllEmployees();
return "listEmployeeView";
}
}
Here is UserDao.java:
#Repository
#Transactional
public class UserDao {
#PersistenceContext
private EntityManager entityManager;
public UserModel getUserByUserId(String userId) {
UserModel user = null;
//EntityManagerFactory emf = Persistence.createEntityManagerFactory("movie-unit");
//entityManager = emf.createEntityManager();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<UserModel> cq = cb.createQuery(UserModel.class);
Root<User> userRoot = cq.from(User.class);
cq.multiselect(
userRoot.get("firstName"),
userRoot.get("middleName"),
userRoot.get("lastName"),
userRoot.get("email"),
userRoot.get("userId"),
userRoot.get("password")
);
cq.where(cb.equal(userRoot.get("userId"), userId));
TypedQuery<UserModel> q = entityManager.createQuery(cq);
user = q.getSingleResult();
System.out.print(user.getUserId()+"&"+user.getPassword());
return user;
}
}
here is web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Hibernate JPA Hello World Application</display-name>
<!-- Configuration file for the root application context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-servlet.xml
</param-value>
</context-param>
<!-- Configuration for the DispatcherServlet -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and here is spring-servlet.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: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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- It register the beans in context and scan the annotations inside beans and activate them -->
<context:component-scan base-package="com.howtodoinjava.demo" />
<!-- This allow for dispatching requests to Controllers by registering
two beans - DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven />
<!-- This helps in mapping the logical view names to directly view files under a certain pre-configured directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- This resolves messages from resource bundles for different locales -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<!-- To validate the posted add employee form -->
<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />
<!-- This produces a container-managed EntityManagerFactory;
rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/baza" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
such as when #Transactional methods are invoked -->
<tx:annotation-driven />
</beans>
Like I said, if I do entitymanager and entitymanagerfactory in java code which is commented here in UserDao.java with persistence.xml like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="movie-unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/baza" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
then everythings works fine.
In mysql server I have privileges like this:
Any % -- USAGE
Any localhost no password USAGE
root 127.0.0.1 no password ALL PRIVILEGES
root ::1 no password ALL PRIVILEGES
root localhost with password ALL PRIVILEGES
Where is problem?
I am trying to get a simple Spring Integration test working to retrieve messages from a JMS queue hosted by HornetQ on JBoss EAP (version 6.4.0.GA running on Windows 7 Pro) running in standalone mode (standalone.bat -c standalone-full.xml).
The JMS test ran fine when using a simple Java JMS program; now, I'm trying to add Spring Integration and I get the following error:
18:29:03,197 ERROR [org.springframework.jms.listener.DefaultMessageListenerContainer]
(org.springframework.jms.listener.DefaultMessageListenerContainer#0-1)
Could not refresh JMS Connection for destination 'anotherQueue' -
retrying in 5000 ms. Cause: AOP configuration seems to be invalid:
tried calling method [public abstract javax.jms.Connection javax.jms.ConnectionFactory.createConnection()
throws javax.jms.JMSException] on target [HornetQQueue[anotherQueue]];
nested exception is java.lang.IllegalArgumentException: java.lang.ClassCastException#511504f4
The Spring config files are:
applicationContext-ordering-inbound-jms-spring-integration.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:aop=...
<bean id="jndiTemplateBilling" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jboss.as.naming.InitialContextFactory</prop>
<prop key="java.naming.provider.url">remote://localhost:4447</prop>
</props>
</property>
</bean>
<bean id="jndiObjectFactoryBeanBilling" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
<property name="lookupOnStartup" value="false" />
<property name="proxyInterfaces">
<list>
<value>javax.jms.QueueConnectionFactory</value>
<value>javax.jms.TopicConnectionFactory</value>
<value>java.io.Externalizable</value>
</list>
</property>
</bean>
<bean id="jndiDestinationResolver"
class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="cache" value="true" />
</bean>
<int-jms:inbound-gateway
request-destination-name="anotherQueue"
request-channel="inboundOrderingBillingJms"
destination-resolver="jndiDestinationResolver"
connection-factory="jndiObjectFactoryBeanBilling" />
<int:channel id="inboundOrderingBillingJms" /> <!-- handled by OrderingBillingInboundEndpoint -->
<context:component-scan base-package="com.att.ordering.endpoints.jms" />
<context:annotation-config />
<context:spring-configured />
<int:annotation-config />
</beans>
and applicationContext-ordering-inbound-jms.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ...">
<context:annotation-config />
<context:spring-configured />
<int:annotation-config />
<context:component-scan base-package="com.att.ordering.endpoints.jms"/>
</beans>
The ServiceActivator class:
package com.att.ordering.endpoints.jms;
import javax.xml.bind.JAXBElement;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class OrderingBillingInboundEndpoint
{
#ServiceActivator(inputChannel = "inboundOrderingBillingJms")
//public void handleMessage(JAXBElement<String> accountNumber)
public void handleMessage(String accountNumber)
{
System.out.println("In OrderingBillingInboundEndpoint.handleMessage - accountNumber=" + accountNumber);
}
}
I bootstrap spring with a WAR; WEB-INF/web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>parentContextKey</param-name>
<param-value>ordering-spring-bootstrap.war.context</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</context-param>
</web-app>
WEB-INF/classes/beanRefContext.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="ordering-spring-bootstrap.war.context"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>/applicationContext-ordering-inbound-jms-spring-integration.xml</value>
<value>/applicationContext-ordering-inbound-jms.xml</value>
</list>
</constructor-arg>
</bean>
</beans>
FOLLOWING ADDED AFTER ARTEM'S INITIAL REPLY
My JNDI name is java:jboss/exported/jms/queue/anotherQueue. It is bound to HornetQQueue[anotherQueue].
Following shows it in JBoss - note: there are 2 JNDI entries; I'm using the second one:
This is correct - I was able to get a Java JMS program (without Spring Integration) working as follows:
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "remote://localhost:4447");
env.put(Context.SECURITY_PRINCIPAL, "appuser");
env.put(Context.SECURITY_CREDENTIALS, "appuser1!");
context = new InitialContext(env);
// JNDI name in JBoss is: java:jboss/exported/jms/queue/anotherQueue
connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory");
destination = (Destination) context.lookup("jms/queue/anotherQueue");
connection = connectionFactory.createConnection("appuser", "appuser1!");
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
consumer.setMessageListener(new MyListener());
connection.start();
I am now trying to get the same simple example working using Spring Integration.
Questions:
(A) Where should I put the user id and password?
(B) Is the following correct? If not, what should it exactly be?
<bean id="jndiTemplateBilling" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jboss.as.naming.InitialContextFactory</prop>
<prop key="java.naming.provider.url">remote://localhost:4447</prop>
</props>
</property>
</bean>
(C) How should I change the following? I removed the proxyInterfaces; what else should change? I don't know how to use jee:jndi-lookup
<bean id="jndiObjectFactoryBeanBilling" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
<property name="lookupOnStartup" value="false" />
</bean>
(D) Does the following stay the same?
<bean id="jndiDestinationResolver"
class="org.springframework.jms.support.destination.JndiDestinationResolver">
<property name="jndiTemplate" ref="jndiTemplateBilling" />
<property name="cache" value="true" />
</bean>
(E) Does the following change?
<int-jms:inbound-gateway
request-destination-name="anotherQueue"
request-channel="inboundOrderingBillingJms"
destination-resolver="jndiDestinationResolver"
connection-factory="jndiObjectFactoryBeanBilling" />
Looks like you are wrong with your jndiObjectFactoryBeanBilling bean definition. It is for
<property name="jndiName" value="java:jboss/exported/jms/queue/anotherQueue" />
what is confirmed by the logs:
on target [HornetQQueue[anotherQueue]];
But it really must be for the javax.jms.ConnectionFactory:
connection-factory="jndiObjectFactoryBeanBilling"
So, just try to change the JNDI name to the correct one.
From other side I have never used all those proxyInterfaces options for JBOSS JNDI resources. They work well as is, e.g.:
<jee:jndi-lookup id="jndiMqConnectionFactory" jndi-name="${mqConnectionFactory}"/>
<jee:jndi-lookup id="auditQueue" jndi-name="queue/AuditQueue"/>
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
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" />