Spring Bean wrong path - java

I am getting this error and I can't figure out why. I believe its the path. Tried to change it several times but no success.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field loginDelegate in com.codeEvaluator.controller.LoginController required a bean of type 'com.codeEvaluator.delegate.LoginDelegate' that could not be found.
Action:
Consider defining a bean of type 'com.codeEvaluator.delegate.LoginDelegate' in your configuration.
Process finished with exit code 1
This is my sprinBeanConfiguration.xml
<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"
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">
<bean id="loginDelegate" class="com.codeEvaluator.delegate.LoginDelegate">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="com.codeEvaluator.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="userDao" class="com.codeEvaluator.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></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/codeevaluator" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
My springWeb.xml
<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"
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.jcg" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
<import resource="springBeanConfiguration.xml"/>
Controller class
package com.codeEvaluator.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.codeEvaluator.delegate.LoginDelegate;
import com.codeEvaluator.viewBean.LoginBean;
#Controller
public class LoginController
{
#Autowired
private LoginDelegate loginDelegate;
#RequestMapping(value="/login",method=RequestMethod.GET)
public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response, LoginBean loginBean)
{
ModelAndView model = new ModelAndView("login");
//LoginBean loginBean = new LoginBean();
model.addObject("loginBean", loginBean);
return model;
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("loginBean")LoginBean loginBean)
{
ModelAndView model= null;
try
{
boolean isValidUser = loginDelegate.isValidUser(loginBean.getUsername(), loginBean.getPassword());
if(isValidUser)
{
System.out.println("User Login Successful");
request.setAttribute("loggedInUser", loginBean.getUsername());
model = new ModelAndView("welcome");
}
else
{
model = new ModelAndView("login");
request.setAttribute("message", "Invalid credentials!!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return model;
}
}
This is a project view.
The login.jsp is inside de jsp package.

change to
<context:component-scan base-package="com.jcg, com.codeEvaluator" />
and your import should be something like this
<import resource="classpath:springBeanConfiguration.xml"/>
or
<import resource="classpath*:springBeanConfiguration.xml"/>

In your "sprinBeanConfiguration.xml" file add those annotations <context:component-scan base-package="com.codeEvaluator" /> and<context:annotation-config> to enable annotation "#Autowired"

Related

I am trying Spring MVC and when I add #Autowired in my controller class I get following error:

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<context:component-scan base-package="com.packt.webstore.domain" />
<context:annotation-config></context:annotation-config>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Webstore"></property>
<property name="username" value="root"></property>
<property name="password" value="password"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productController': Unsatisfied
dependency expressed through field 'productRepository'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'productRepositoryImpl': Unsatisfied
dependency expressed through method 'setDataSource' parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'javax.sql.DataSource' available: expected at
least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
package com.packt.webstore.domain.repository.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
import com.packt.webstore.domain.repository.ProductRepository;
#Repository
public class ProductRepositoryImpl implements ProductRepository {
private NamedParameterJdbcTemplate jdbcTemplate;
#Autowired
private void setDataSource(DataSource dataSource) {
this.jdbcTemplate=new NamedParameterJdbcTemplate(dataSource);
}
#Override
public List<Product> getAllProducts() {
Map<String, Object>params=new HashMap<String,Object>();
List<Product>result=jdbcTemplate.query("SELECT * FROM PRODUCTS", params, new ProductMapper());
return result;
}
private static final class ProductMapper implements org.springframework.jdbc.core.RowMapper<Product> {
public Product mapRow(ResultSet rs,int rownum) throws SQLException{
Product product=new Product();
product.setName(rs.getString("name"));
return product;
}
}
}
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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">
<mvc:annotation-driven enable-matrix-variables="true"></mvc:annotation-driven>
<context:component-scan base-package="com.packt"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
package com.packt.webstore.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.packt.webstore.domain.repository.ProductRepository;
#Controller
public class ProductController {
#Autowired
private ProductRepository productRepository;
#RequestMapping("/products")
public String list(Model model) {
model.addAttribute("products",productRepository.getAllProducts());
return "products";
}
}
it looks like you din't configure data-source in xml file
try to add below configuration in xml file
<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/yourdbname" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
You need to define DataSource bean in your XML file then only use can use #Autowired annotation to configure that bean or you can use #Autowired annotation in the following way:
#Autowired
private NamedParameterJdbcTemplate jdbcTemplate;

#Transactional annotation in Spring

I have written the below code to implment the transaction management of spring using #transactional annotation. I still feel some changes are required
in my DAO layer. May I know what changes are required . Thanks in advance
#Controller
public class RestController {
#Autowired
DataServices dataServices;
#RequestMapping(value = "/v1/dist_list/{emailId}/members", method = RequestMethod.GET)
public #ResponseBody String getDistributionListMember(#PathVariable String emailId) throws Exception, SpringException {
String retStatus = null;
retStatus = dataServices.getDistributionListMember(emailId, callerId);
]
}
}
DataServices.java
package com.uniteid.services;
import com.uniteid.model.AIWSuser;
public interface DataServices {
public String getDistributionListMember(final String emailId, final String callerID) throws Exception;
}
Below is my service layer where I added the trasactional attribute
package com.uniteid.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.uniteid.dao.DataDao;
import com.uniteid.model.AIWSuser;
#Service("dataService")
public class DataServicesImpl implements DataServices {
#Autowired
DataDao dataDao;
#Transactional
public String getDistributionListMember(String emailId, String callerID)
throws Exception {
return dataDao.getDistributionListMember(emailId, callerID);
}
}
Below is my spring-config file
<?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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<context:component-scan base-package="com.uniteid.controller" />
<mvc:annotation-driven
content-negotiation-manager="contentNegociationManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:uniteidrest.properties" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url">
<value>${eidms.url}</value>
</property>
<property name="username">
<value>${eidms.username}</value>
</property>
<property name="password">
<value>${eidms.password}</value>
</property>
</bean>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"
/> <property name="url" value="jdbc:oracle:thin:#nyvm0467.ptc.un.org:1521:EIDMSUAT"
/> <property name="username" value="DBO_EIDMSUAT" /> <property name="password"
value="NewPassDBO_EIDMSUAT" /> </bean> -->
<bean id="contentNegociationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/json" />
<property name="ignoreAcceptHeader" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.uniteid.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.connection.pool_size">10</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 id="dataDao" class="com.uniteid.dao.DataDaoImpl"></bean>
<bean id="dataServices" class="com.uniteid.services.DataServicesImpl"></bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
It still feel I have not implemented the Transactional management properly in the below code. May I know what part of the code can be removed for me to implement it
package com.uniteid.dao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import com.uniteid.controller.RestController;
import com.uniteid.model.AIWSuser;
import com.uniteid.model.User;
public class DataDaoImpl implements DataDao
{
#Autowired
\
SessionFactory sessionFactory;
Session session = null;
Transaction tx = null;
static final Logger logger = Logger.getLogger(DataDaoImpl.class);
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
final String[] returnVal2 = { "" };
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
CallableStatement stmt = null;
String returnVal = "";
stmt = connection.prepareCall("{?=call WS_Distributionlistmember(?,?)}");
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.setString(2, emailId);
stmt.setString(3, callerID);
stmt.execute();
returnVal = stmt.getString(1);
logger.info("RETURN VALUE in getDistributionListMember method :::::: " + returnVal);
returnVal2[0] = returnVal;
logger.info("Return Value " + returnVal);
stmt.close();
}
});
tx.commit();
session.close();
return returnVal2[0];
}
}
Your code:
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.openSession();//This is bad
tx = session.beginTransaction();//This is bad
tx.commit();//This is bad
session.close();//This is bad
Correct should be:
public String getDistributionListMember(final String emailId, final String callerID) throws Exception {
session = sessionFactory.getCurrentSession();//good way
It is because you told spring to autowired sessionFactory and from now on spring is managing your hibernate session not you. So getCurrentSession() is correct way.
#M. Deinum Thanks to point it out.
Remove bean declaration for bean id transactionManager and set txManager instead of transactionManager in transaction-manager value. As you are using hibernate with spring so HibernateTransactionManager should be used instead of DatabaseTransactionManager to define transaction boundary. DatabaseTransactionManager is used when you directly interact with data source without using any ORM or JPA framework.
In your service class define transaction boundary for method as below annotation
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)

Spring Boot integration with MongoDB

I am trying to integrate monodb with my springBoot application 1st time, But I am stuck with the error
My code is below
package com.myProject.customerview;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
#EnableScheduling
#ImportResource("classpath*:spring/application-context.xml")
#ComponentScan({ "com.myproject.payments", "com.myproject.customerview" })
// #EnableJpaRepositories("com.myproject.customerview.repository")
#EnableMongoRepositories
#SpringBootApplication
public class CustomerViewApplication {
public static void main(String args[]) {
SpringApplication application = new SpringApplication(
CustomerViewApplication.class);
application.run(args);
}
}
and Controller
package com.myproject.customerview.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.myproject.customerview.constants.RestURIConstants;
import com.myproject.customerview.response.ServiceResponse;
import com.myproject.customerview.service.CustomerViewService;
#RestController
#RequestMapping(RestURIConstants.CUSTOMER_VIEW)
public class CustomerViewController {
#Autowired
private CustomerViewService customerViewService ;
#RequestMapping(value = RestURIConstants.USER_ID, method = RequestMethod.GET)
public ServiceResponse<String> getMirrorAccountReport(
#PathVariable("userId") String userId, HttpServletRequest servletRequest)
throws Exception {
ServiceResponse<String> serviceResponse = new ServiceResponse<String>();
String response = "success:" ;
customerViewService.saveCustomerViewEntity();
serviceResponse.setResponse(response);
return serviceResponse;
}
}
service
package com.myproject.customerview.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.myproject.customerview.entity.CustomerViewEntity;
import com.mmyproject.customerview.repository.CustomerViewRepository;
import com.myproject.customerview.service.CustomerViewService;
#Service
public class CustomerviewServiceImpl implements CustomerViewService {
#Autowired
private CustomerViewRepository customerRepository ;
#Override
public void saveCustomerViewEntity() {
CustomerViewEntity entity = new CustomerViewEntity() ;
//setting data in enity....
customerRepository.saveCustomerView(entity);
}
}
dao interface layer
package com.myproject.customerview.dao;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Sort;
import com.myproject.customerview.entity.CustomerViewEntity;
public interface CustomerViewMongoDao {
public void saveCustomerView(CustomerViewEntity entity) ;
}
its impl
package com.myproject.customerview.dao.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import com.myproject.customerview.constants.CustomerViewConstants;
import com.myproject.customerview.dao.CustomerViewMongoDao;
import com.myproject.customerview.entity.CustomerViewEntity;
#Repository
public class CustomerViewMongoDaoImpl implements CustomerViewMongoDao{
#Autowired
MongoTemplate mongoTemplate ;
#Override
public void saveCustomerView(CustomerViewEntity entity) {
mongoTemplate.insert(entity, CustomerViewConstants.CUSTOMER_VIEW_COLLECTION);
}
}
its repository
package com.myproject.customerview.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.myproject.customerview.dao.CustomerViewMongoDao;
import com.myproject.customerview.entity.CustomerViewEntity;
public interface CustomerViewRepository extends MongoRepository<CustomerViewEntity,String>, CustomerViewMongoDao {
}
and application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="classpath:/resources" />
<bean id="imsPlaceholderConfig" class="com.myproject.customerview.utils.SpringPropertiesUtil">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="locations">
<list>
<value>file:${config.path}/app.properties</value>
<value>file:${config.path}/api.properties</value>
<value>file:${config.path}/db.properties</value>
<value>classpath*:*application.properties</value>
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
</bean>
<!-- <mongo:mongo replica-set="127.0.0.1:27017,127.0.0.1:27017,127.0.0.1:27017" id = "mongo" />
<mongo:db-factory dbname="customer_view" mongo-ref="mongo" id="mongoDbFactory"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.myproject.customerview.repository" />
-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="${payment.customerview.database.driverClassName}" />
<property name="url" value="${payment.customerview.database.url}" />
<property name="username" value="${payment.customerview.database.username}" />
<property name="password" value="${payment.customerview.database.password}" />
<property name="maxActive" value="${payment.customerview.database.maxactive}" />
<property name="maxWait" value="${payment.customerview.database.maxwait}" />
<property name="maxIdle" value="${payment.customerview.database.maxIdle}" />
<property name="initialSize" value="${payment.customerview.database.inititalsize}" />
<property name="minIdle" value="${payment.customerview.database.minIdle}" />
<property name="timeBetweenEvictionRunsMillis"
value="${payment.customerview.database.timebetweenevictionrunsmillis}" />
<property name="minEvictableIdleTimeMillis"
value="${payment.customerview.database.minevictableidletimemillis}" />
</bean>
<!-- MyBatis related beans -->
<bean id="sqlSessionFactoryMybatis" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:myBatis/sqlmap-config.xml" />
</bean>
<bean name="myBatisIMSDB" id="myBatisIMSDB"
class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactoryMybatis" />
<constructor-arg index="1" value="REUSE" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"
value="com.myproject.customerview.dao.mapper" />
<property name="sqlSessionTemplateBeanName" value="myBatisIMSDB"></property>
</bean>
</beans>
I am getting following error.
java.lang.IllegalStateException: Failed to introspect annotations: class org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfigureRegistrar$EnableMongoRepositoriesConfiguration
I have wrongly added this dependency in my pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
instead of this when i used
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
my projects starts working fine.

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

Sending mail with the user entered username and password in Spring

My application requires sending a mail from the user entered user name and password using Spring API. Here's how my Application Context file look.
<?xml version="1.0" encoding="UTF-8"?>
<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:task="http://www.springframework.org/schema/task"
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/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="net.mail" />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="25"/>
<property name="username" value="xyz#xyz.com" />
<property name="password" value="xyz" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
</beans>
And my Controller looks like following
package net.mail;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class MailController
{
#Autowired
MailSender sender;
#ResponseBody
#RequestMapping("/send")
public String sendMailToIt(HttpServletRequest request)
{
try
{
String from=request.getParameter("from");
String to=request.getParameter("to");
String sub=request.getParameter("subject");
String username=request.getParameter("username");
String password=request.getParameter("password");
//username and password should be used for authentication
SimpleMailMessage mail=new SimpleMailMessage();
mail.setFrom(from);
mail.setTo(to);
mail.setSubject(sub);
mail.setText("hello");
sender.send(mail);
}
catch(Exception e)
{
e.printStackTrace();
return "Exception Occured";
}
return new String("mail sent");
}
}
Now my requirements are
I don't want to use the properties file.
I want to username and password to be the ones entered by user.
I only found solutions using the properties file. but in my case i do not want to use that file.
Is there any way of doing so?
You can set in your MailController by getting data from the user ( set or override based on your requirement)
public String sendMailToIt(HttpServletRequest request)
{
.....
JavaMailSenderImpl jMailSender = (JavaMailSenderImpl)sender;
jMailSender.setUsername(userName);
jMailSender.setPassword(password);
....
jMailSender.send(mail);
....
}

Categories