Yet Another ApplicationContext is Null [duplicate] - java

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 5 years ago.
I'm having trouble autowiring a Spring bean in my application. This is something I've done before in other applications with success, but for some reason I'm getting stumped. I've googled around, and have found many folks having the same troubles, and the warnings that go along with using the getApplicationContext() approach but no answers that helped me. I understand the warnings and still have a case where I want to do it this way, then maybe I'll get it working using AspectJ and compile time weaving.
Here is my setup:
applicationContext.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:oxm="http://www.springframework.org/schema/oxm"
xmlns:util="http://www.springframework.org/schema/util"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:property-placeholder location="classpath:widgetClient.properties"/>
<context:component-scan base-package="com.myCompany.widget.domain" />
<context:component-scan base-package="com.myCompany.widget.services" />
<context:annotation-config />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="heartbeat" class="com.company.widget.domain.CheckWidgetServerHeartbeat" destroy-method="destroy">
<constructor-arg type="java.lang.Integer" name="interval" value="${heartbeat.interval}"/>
<constructor-arg type="java.lang.Integer" name="timeout" value="${heartbeat.timeout}"/>
<constructor-arg type="java.lang.Integer" name="unhealthyThreshold" value="${unhealthy.threshold}"/>
<constructor-arg type="java.lang.Integer" name="healthyThreshold" value="${healthy.threshold}"/>
<constructor-arg type="java.lang.Integer" name="backupVerifyTime" value="${backup.verify.time}"/>
<constructor-arg type="java.lang.String" name="apiServerUrl" value="${api.server.url}" />
</bean>
</beans>
BaseService.java
package com.company.widget.services;
import com.company.widget.domain.CheckWidgetServerHeartbeat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class BaseService{
#Autowired
private ApplicationContext appContext;
public BaseService(){}
public CheckWidgetServerHeartbeat getHeartbeat(){
return (CheckWidgetServerHeartbeat) appContext.getBean("heartbeat");
}
}
Heartbeatservice.java
package com.company.widget.services;
import org.springframework.stereotype.Service;
import org.apache.log4j.Logger;
#Service
public class HeartbeatService extends BaseService{
private static final Logger logger = Logger.getLogger(HeartbeatService.class);
public HeartbeatService(){}
public Boolean isHealthy(){
return getHeartbeat().check();
}
}
CompanyWidgetClient.java
package com.company.widget.domain;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Locale;
import java.util.ResourceBundle;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.*;
import com.company.widget.services.HeartbeatService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class CompanyWidgetClient{
#Autowired
private HeartbeatService heartbeatService;
public CompanyWidgetClient(String settingsXmlFilePath, HttpServletRequest request){
if(settingsXmlFilePath != null){
configuration = new CompanyWidgetConfiguration(settingsXmlFilePath, request);
}
if(request != null){
this.request = request;
}
//Use API server URL from settings file if it is present
if (configuration.getProperty("api_server_url") != null) {
this.apiServerUrl = configuration.getProperty("api_server_url");
log.debug("Set api_server_url to " + this.apiServerUrl + " which was found in settings.xml");
}
}
public CompanyWidgetClient(CompanyWidgetConfiguration configuration, HttpServletRequest request){
if(configuration != null){
this.configuration=configuration;
}
if(request != null){
this.request = request;
}
//Use API server URL from settings file if it is present
if (configuration.getProperty("api_server_url") != null) {
this.apiServerUrl = configuration.getProperty("api_server_url");
log.debug("Set api_server_url to " + this.apiServerUrl + " which was found in settings.xml");
}
}
public CompanyWidgetClient(){}
private CompanyWidgetResponse requestWidget(){
if(heartbeatService.isHealthy()){
do stuff...
}
index.jsp
<%# page import="com.company.widget.domain.*" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%
CompanyWidgetClient widgetClient = new CompanyWidgetClient("/WEB-INF/settings.xml", request);
String companyWidgetComponent = widgetClient.createWidget();
%>
...
HTML stuff
...
<div id="widget">
<%=companyWidgetComponent%>
</div>
...
The error:
500
org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 5
2: <%# page contentType="text/html;charset=UTF-8" language="java" %> 3: <% 4: CompanyWidgetClient widgetClient = new CompanyWidgetClient("/WEB-INF/settings.xml", request); 5: String companyWidgetComponent = widgetClient.createWidget(); 6: %> 7: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 8: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.company.widget.domain.CompanyWidgetClient.requestWidget(CompanyWidgetClient.java:553)
com.company.widget.domain.CompanyWidgetClient.createWidget(CompanyWidgetClient.java:603)
org.apache.jsp.index_jsp._jspService(index_jsp.java:67)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Observations:
I know I'm missing something as it required the default constructor to be present on the CompanyClient object, and it logs that it builds a CompanyClient object on deployment. I guess I'm not very clear on scope when it comes to Spring application context. My understanding was that a singleton bean should be available using the application context irrespective of the scope of the calling bean. Any and all help is very appreciated!

When you are instantiating the CompanyWidgetClient directly:
new CompanyWidgetClient(...)
you are not giving the spring DI container a chance to inject an instance of HeartbeatService - so its null.
When getting an instance of CompanyWidgetClient - retrieve the instance from Spring Applicaiton Context (via getBean() or similar) - so the HeartbeatService will have been Autowired.

Related

Java controller giving 404 error on live server

I m setting up my java web application on the server but the rest controller is giving 404 error.
All is working fine on my local system.
This is my 1st project in java hibernate spring.
Below is my code:
UserLoginController.java
package org.jasyatra.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.jasyatra.model.User;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.service.UserLoginService;
import org.jasyatra.service.LoginAuthTokenService;
#RestController
public class UserLoginController {
#Autowired
UserLoginService userLoginService;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#RequestMapping(value = "/user/login", method = RequestMethod.POST, headers = "Accept=application/json")
public Map login(#RequestBody User parameters) {
List<User> loginResponse = userLoginService.login(parameters);
Map<String, String> response = new HashMap<>();
if (loginResponse.size() > 0) {
response.put("result", "true");
response.put("id", Integer.toString(loginResponse.get(0).getId()));
response.put("type", loginResponse.get(0).getType());
response.put("firstName", loginResponse.get(0).getFirstName());
response.put("lastName", loginResponse.get(0).getLastName());
response.put("permissions", loginResponse.get(0).getPermissions());
List<LoginAuthToken> responseToken = loginAuthTokenService.getLatestToken(loginResponse.get(0).getId(),loginResponse.get(0).getType());
response.put("token", responseToken.get(0).getToken());
} else {
response.put("result", "false");
response.put("message", "Invalid mobile no or password!");
}
return response;
}
}
UserLoginDAO.java
package org.jasyatra.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jasyatra.service.HashService;
#Repository
public class UserLoginDAO {
#Autowired
private SessionFactory sessionFactory;
public List<User> login(User parameters) {
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where mobileNo=:mobileNo and password=:password and status=:status");
query.setParameter("mobileNo", parameters.getMobileNo());
query.setParameter("password", HashService.getHash(parameters.getPassword(), "SHA1"));
query.setParameter("status", "active");
List<User> response = query.list();
return response;
}
}
UserLoginService.java
package org.jasyatra.service;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.jasyatra.dao.UserLoginDAO;
import org.jasyatra.dao.LoginAuthTokenDAO;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class UserLoginService {
#Autowired
UserLoginDAO userLoginDao;
#Autowired
LoginAuthTokenDAO loginAuthTokenDAO;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#Transactional
public List<User> login(User parameters) {
List<User> login = userLoginDao.login(parameters);
LoginAuthToken loginAuthToken = new LoginAuthToken();
if (login.size() > 0 && login.get(0).getId() > 0) {
try {
loginAuthToken.setLoginId(login.get(0).getId());
loginAuthToken.setLoginType(login.get(0).getType());
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
String token = HashService.getHash(generatedString, "SHA1");
loginAuthToken.setDateCreated(new Date());
loginAuthToken.setToken(token);
loginAuthTokenService.save(loginAuthToken);
} catch (Exception e) {
e.printStackTrace();
}
}
return login;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/"/>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/jasyatra" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.jasyatra.model.User</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="268435456"/>
</beans:bean>
<context:component-scan base-package="org.jasyatra" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<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>
</web-app>
The main issue i have is, it is able to run index.jsp but not the controller. What can be the issue?
Please guide me in right direction.
Thanks
you can not open that url in browser because it is POST service, you can only open GET url in browser. you need to add a body while hitting that url to test
your service you can use postman.
no need to send "Accept" header this way, you can use however following attribute instead if you expect a json body with the post request :
#RequestMapping(value = "/user/login", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE);
if you want to get "Accept" header value of your request you can get it like :
public Map login(#RequestBody User parameters,#RequestHeader(value="Accept") String accept){
....

Spring can not automatically inject dubbo service

Development tools: idea java
Use the framework: spring + springmvc + mybatis + dubbo
dubbo is a high-performance, java based, open source RPC framework.
When I use spring #autowired error, as shown in Figure 1.
But when I was in java annotations, it works fine, as shown in Figure II.
Figure 1
Figure 2
code1. the spring/applicationContext-service.xml for service.
code2. the spring/spring-mvc.xml for contoller.
code3. Service
code4. Controller (Here's a problem, with #autowired can not be automatically injected)
Thanks!
The code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" 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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">
<context:component-scan base-package="xyz.maojun.service"/>
<dubbo:application name="manager"/>
<dubbo:registry protocol="zookeeper"
address="localhost:2181"/>
<dubbo:protocol name="dubbo" port="20880"/>
<dubbo:service interface="xyz.maojun.service.ItemService" ref="itemServiceImpl" timeout="600000"/>
</beans>
More code:
<?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"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">
<context:component-scan base-package="xyz.maojun.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"value="/WEB-INF/jsp/"/>
<property name="suffix"value=".jsp"/>
</bean>
<mvc:resources mapping="/css/**"location="css/"/>
<mvc:resources mapping="/js/**"location="js/"/>
<dubbo:application name="manager-web"/>
<dubbo:registry protocol="zookeeper"address="localhost:2181"/>
<dubbo:reference interface="xyz.maojun.service.ItemService"id="itemService"/>
</beans>
ItemService code:
package xyz.maojun.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.maojun.common.pojo.EasyUIDateGridResult;
import xyz.maojun.mapper.TbItemMapper;
import xyz.maojun.pojo.TbItem;
import xyz.maojun.pojo.TbItemExample;
import xyz.maojun.service.ItemService;
import javax.annotation.Resource;
import java.util.List;
#Service
public class ItemServiceImpl implements ItemService {
#Autowired
private TbItemMapper tbItemMapper;
#Override
public TbItem getItemById(long itemid) {
TbItemExample example = new TbItemExample();
TbItemExample.Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(itemid);
List<TbItem> list = tbItemMapper.selectByExample(example);
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}
The controller:
package xyz.maojun.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.maojun.pojo.*;
import xyz.maojun.service.ItemService;
import javax.annotation.Resource;
#Controller
public class ItemController {
#Resource // i want to use #autowired ,but it not work
private ItemService itemService;
#RequestMapping("/item/{itemId}")
#ResponseBody
public TbItem getItemById(#PathVariable long itemId) {
TbItem tbItem = itemService.getItemById(itemId);
return tbItem;
}
}
I already got this answer, it is Intellij IDEA problem.When running the project does not have this error, I use the spring annotation, Intellij IDEA will can not find the bean then make an error. Ignore false positives

Failed to load ApplicationContext while running test cases

when i am running my spring integration junit class i am getting above exception.
here is my class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BpmControllerTest {
#Autowired
private BpmProcessorDaoImplTest bpmProcessorDao;
#Test
public void testRun() throws UnexpectedInputException, ParseException, NonTransientResourceException, Exception {
List<User>user=bpmProcessorDao.testRead();
Assert.assertEquals(0,user.size());
}
}
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
here is my stack trace..
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 37 more
can any body please tell me how to write this line
#ContextConfiguration(locations = "classpath:applicationContext.xml")
some places in google i found like this
#ContextConfiguration(locations = "classpath:**/applicationContext.xml")
what is the difference of these two
and when i am writing this line with stars i am getting different exception
here is my stack trace.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.tcs.test.dao.BpmProcessorDaoImplTest] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
and one thing that my application is only dynamic web project no maven,no ant .
can any body please tell me how to run my test cases successfully..
here is my applicationContext.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
">
<tx:annotation-driven />
<tx:jta-transaction-manager/>
<context:component-scan base-package="com.tcs.test" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.19.8.159:1521/OIM.itba.gov.in" />
<property name="username" value="AppDB"></property>
<property name="password" value="AppDB"></property>
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="runScheduler" class="com.tcs.controller.BpmControllerTest" />
<task:scheduled-tasks>
<task:scheduled ref="runScheduler" method="testRun" cron="0 0/1 * * * ?" />
</task:scheduled-tasks>
</beans>
all my test java files in side test source folder.
and all the files in side the package's which prefix is com.tcs.test
here is my daoImpl class
package com.tcs.test.dao;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import com.tcs.controller.BPMConstants;
import com.tcs.controller.User;
#Repository
public class BpmProcessorDaoImplTest implements BpmProcessorDaoTest{
private static final Logger logger=Logger.getLogger(BpmProcessorDaoImplTest. class);
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
#Test
public void testWrite() {
}
#Test
public void testUpdateStatus() {
}
#Test
public List<User> testRead() {
String query=null;
List<User>users=null;
try{
// jdbcTemplate.setDataSource(dataSource);
// query=messageSource.getMessage(BPMConstants.QUERY,null,Locale.US);
query="select taskoutcome,seqNo,hash_mapdata,userid,status,taskId from com_tt_bpm_batch , "
+ "wftask where status='ACTIVE' and request_id=instanceid and state='ASSIGNED'";
logger.info("query");
jdbcTemplate.setFetchSize(20);
users=jdbcTemplate.query(query, new ResultSetExtractor<List<User>>(){
List<User> userList = new ArrayList<User>();
#SuppressWarnings("unchecked")
#Override
public List<User> extractData(ResultSet rs) throws SQLException,DataAccessException {
while(rs.next()){
logger.info("fetching records from db");
User user = new User();
user.setTaskOutcome(rs.getString(BPMConstants.TASK_OUTCOME));
user.setUserId(rs.getString(BPMConstants.USER_ID));
user.setStatus(rs.getString(BPMConstants.STATUS));
user.setTaskId(rs.getString(BPMConstants.TASK_ID));
user.setSeqNo(rs.getLong(BPMConstants.SEQ_NO));
user.setUserComment("nothing");
Blob blob=rs.getBlob(BPMConstants.HASH_MAPDATA);
try{
if(blob!=null && !blob.equals("")){
int blobLength = (int) blob.length();
byte[] blobAsBytes = blob.getBytes(1, blobLength);
ByteArrayInputStream bos = new ByteArrayInputStream(blobAsBytes);
ObjectInputStream out=null;
out = new ObjectInputStream(bos);
HashMap<String, Object> map=null;
map = (HashMap<String, Object>)out.readObject();
user.setMap(map);
}
userList.add(user);
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from blob "+e.getStackTrace());
}
}
return userList;
}
});
}catch(Exception e){
logger.error(e.getMessage());
logger.error("Exception at UserRowMapper class while reading data from db "+e.getStackTrace());
}
return users;
}
}
1)
i have my applicationContext inside web-inf and i am using all the spring 4.x jars.
The web-inf folder is not (without hacks and problems) accessabel while running the tests.
So the short and easy solution is to put that spring config files in:
(if you use maven): src\main\resources
(if you do not use maven): your java source file root folder
(if you do not use maven but eclipse): create an extra folder (for example resources), put the files in that folder, and then make this folder a eclipse source folder (right click that folder in the package explorer and then choose "Build Path" / "Use as Source Folder")
2)
your BpmProcessorDaoImplTest does not look like a valid test for me.
Either it is a Test case - then its methods have #Test annotations and the class itself have the #ContextConfiguration configuration that points to your configuration file. Or is is a Repository then it has a #Repository annotation and not #Test or #ContextConfiguration. annotations. But I never saw a class that mixed this.
So try this:
#ContextConfiguration("classpath:applicationContext.xml")
#Transactional //make your tests run in an transaction that gets rolled back after the test
public class BpmProcessorDaoImplTest {
/** Class under test */
#Autowired
private BpmProcessorDao dbmProcessorDao;
#Autowired
JdbcTemplate jdbcTemplate;
#Autowired
private ResourceBundleMessageSource messageSource;
//just to make the example test usefull
#PersistenceContext
private EntityManager em
#Test
public void testWrite() {
DbmProcessor entity = ...;
...
this.dbmProcessorDao.save();
...
em.flush(); //make sure that every is saved before clear
em.clear(); //clear to make read(id) read the entity from the database but not from l1-cache.
int id = entity.getId();
...
DbmProcessor reloadedEntity = this.dbmProcessorDao.read(id);
//getName is just an example
assertEquals(entity.getName(), dbmProcessorDao.getName());
}
}
This will occure when applicationContext.xml cannot be found in class path
Possible solutions :
add directory containing applicationContext.xml to classpath.
give relative path of applicationContext.xml
give absolute path of applicationContext.xml
If 3rd solution worked for you would mean that applicationContext.xml was not in classpath.

declaration can be found for element 'context:property-placeholder'. Spring 4

I browsed around 30 webpages and 50 articles about this and it's still not working.
Here is my code its really simple I'm only a Spring beginner.
App.java
package com.procus.spring.simple.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* #author procus
*/
public class App {
public static void main(String[] args) {
ApplicationContext con = new ClassPathXmlApplicationContext("SpringBeans.xml");
SampleSimpleApplication sam = (SampleSimpleApplication) con.getBean("sam");
sam.run(args);
}
}
SampleSimpleApplication.java
package com.procus.spring.simple.simple;
import com.procus.calculator.basic.BasicCalculator;
import com.procus.spring.simple.simple.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackageClasses = BasicCalculator.class)
public class SampleSimpleApplication implements CommandLineRunner {
// intentional error
#Autowired
BasicCalculator calculator;
// Simple example shows how a command line spring application can execute an
// injected bean service. Also demonstrates how you can use #Value to inject
// command line args ('--name=whatever') or application properties
#Autowired
private HelloWorldService helloWorldService;
public SampleSimpleApplication() {
}
#Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
HelloWorldService.java
package com.procus.spring.simple.simple.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
#Component
#Configuration
#PropertySource(value = { "classpath:application.properties" })
public class HelloWorldService {
#Value("${app.name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
SpringBeans.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-4.0.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:property-placeholder location="classpath*:application.properties"/>
<bean id="DBProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<value>classpath*:application.properties</value>
</property>
</bean>
<bean id="sam" class="com.procus.spring.simple.simple.SampleSimpleApplication"/>
<bean id="serv" class="com.procus.spring.simple.simple.service.HelloWorldService">
<property name="name" value="Jano" />
</bean>
<bean id="calc" class="com.procus.calculator.basic.BasicCalculator">
<constructor-arg value="1.0"/>
</bean>
</beans>
And in resources folder is my application.properties file which contains only app.name=Phil
Exception in thread "main"
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
Line 12 in XML document from class path resource [SpringBeans.xml] is
invalid; nested exception is org.xml.sax.SAXParseException;
lineNumber: 12; columnNumber: 81; cvc-complex-type.2.4.c: The matching
wildcard is strict, but no declaration can be found for element
'context:property-placeholder'.
I really tried most of solutions which I found at stackoverflow and few other forums. I`m really new in spring and I will appreciate any help.
In your springbeans.xml you've specified the location as "classpath*:application.properties" classpath with a * whereas in your HelloWorldService.java you've specified the location as "classpath:application.properties". There is a discrepancy in the two locations.
Besides the problem lies in the SpringBeans.xml schema declaration. It is incorrect & incomplete.
After the context declaration http://www.springframework.org/schema/context/spring-context-4.0.xsd is missing
check this this & this
Ideally it should be
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
I am unable to comment -
What i see is you are writing : <context:property-placeholder location="classpath*:application.properties"/>
Why is there a * after classpath.
It should work with - <context:property-placeholder location="classpath:application.properties"/>
Else -
You can use -
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
In you Heloworld bean
<bean id="helloworld" class ="package.HelloWorldService" >
<property name="name" value="${app.name}" />
</bean>

Can't find controller in Spring annotation for AJAX

I tried to load data via AJAX in Spring 3.0, but the AJAX URL can't find the controller in Spring, and I don't know how to fix this.
I know while server start it looks up the URL and gets data but here I can't crate annotation properly in spring and I have searched the web a lot but have not succeeded.
My Java class:
package springactiontest;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import Dao.dao;
#Controller
//#RequestMapping("/employee")
public class mainclass {
#RequestMapping(value="/AddUser",method=RequestMethod.GET)
public #ResponseBody static String data(ModelMap model, HttpSession session) {
System.err.println("err ocured");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
setvalueclass studentJDBCTemplate =(setvalueclass)context.getBean("actionclass");
System.out.println("------list district--------" );
JSONArray newtest=new JSONArray();
List<dao> students = studentJDBCTemplate.listStudents();
for (dao record : students)
{
JSONObject ob=new JSONObject();
System.out.print("ID test: " + record.getDistrict());
ob.put("distrct", record.getDistrict());
newtest.add(ob);
}
System.err.println("error");
String res=newtest.toString();
System.err.println("error"+res);
return res;
}
}
Jsp:
$("document").ready(function () {
alert("distrcict");
dist_pop();
});
function dist_pop() {
var urlService="http://tamilnilam:8080/SpringTest";
$.ajax({
url: urlService +'/AddUser',
type: 'GET',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("sucess")
},
error: function (jqXHR, exception) {
alert("Error Occured in dist pop");
}
});
}
applicationcontext.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="springactiontest.setvalueclass"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://10.163.2.165:5434/land_rural"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<bean id="actionclass" class="springactiontest.setvalueclass">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Looks like component-scan is missing, it helps Spring to detect and instantiate Spring beans which are annotated with #Component, #Service,#Repository, #Controller, #Endpoint etc
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.your.controller.package" />
// Rest of the bean defiantions
</beans>
For reference : Spring MVC tutorial

Categories