How to catch Spring bean creation error? - spring-mvc

AdminService.java
package service;
import java.awt.Window.Type;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
// 로그인
public HashMap<String, Object> login(String id,String pw)
{
HashMap<String, Object> result = memberDao.selectOne(id);
if(result != null) // 존재하는 값이 있으면
{
String opwd = (String) result.get("pw"); // opwd = 존재하는값의 pw값을 가져온 값
if(opwd.equals(pw))
{
return result; // true면 존재하는값을 반환
}
else
{
return null;
//return null; // 아니면 값을 반환하지 않음.
}
}
else // 존재하는 값이 없다면
{
return null;
}
}
// 아이디 체크
public boolean idCheck(String loginPerson)
{
HashMap<String, Object> user = memberDao.selectOne(loginPerson);
if(user != null)
{
return false;
}
else
{
return true;
}
}
// 멤버 추가
public boolean insertMember(Member member)
{
if(idCheck(member.getId()))
{
memberDao.insertMember(member);
return true;
}
else
{
return false;
}
}
public HashMap<String, Object> getMemberInfo(String id)
{
return memberDao.selectOne(id);
}
// 회원 수정
public void memberUpdate(HashMap<String, Object> params)
{
System.out.println("params is : " + params);
memberDao.updateMember(params);
}
// 회원삭제
public boolean memberDelete(String id,String pw)
{
HashMap<String, Object> user = memberDao.selectOne(id);
String pw2 = (String) user.get("pw");
System.out.println("id and pw is : " + id + "/" + pw);
System.out.println("pw2 is : " + pw2);
if(pw2.equals(pw))
{
memberDao.deleteMember(id);
System.out.println("return true");
return true;
}
else
{
System.out.println("return false");
return false;
}
}
}
AdminController.java
package controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.AdminService;
import service.MemberService;
#Controller
public class AdminController
{
#Autowired
public AdminService aService;
// 관리자 로그인 폼 페이지
#RequestMapping("admin.do")
public String adminLoginPage()
{
return "adminLoginPage";
}
// 관리자 로그인했을 시 요청
#RequestMapping("adminLoginOK.do")
#ResponseBody
public String adminMainPage(#RequestParam(required=false) String id, #RequestParam(required=false)String pw,HttpSession session,HttpServletRequest req,HttpServletResponse resp)
{
HashMap<String, Object> adminLoginIdentify = aService.adminLogin(id, pw);
//if(session.getAttribute("id") == null){System.out.println("zzz kkk");}
//String admin_id = (String) session.getAttribute("id");
if(adminLoginIdentify != null)
{
return "1";
}
else
{
return "0";
}
}
#RequestMapping("adminPage.do")
public String adminPage(
#RequestParam(required = false) String keyword,
#RequestParam(defaultValue="0") int type,
HttpSession session,HttpServletRequest resquest,HttpServletResponse response) throws IOException
{
ModelAndView mav = new ModelAndView();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("type", type);
params.put("keyword", keyword);
System.out.println(params);
return "adminMainPage";
}
}
adminDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IAdminDAO">
<select id="selectOne" parameterType="Strig" resultType="java.util.HashMap">
select * from member where id = #{id}
</select>
<select id="selectMemberAll" resultType="java.util.HashMap">
select * from member
</select>
</mapper>
AdminDao.java
package dao;
import java.util.HashMap;
public interface IAdminDAO
{
public HashMap<String, Object> selectOne(String id);
}
The code before modifying the applicationContext file is shown below.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath*:dao/mapper/*.xml"></property>
</bean>
<bean id="memberDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="dao.IMemberDAO"></property>
</bean>
</beans>
This is the appliCation code after the modification.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:dao/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="model"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
The project worked well before the applicationContext file was modified,
but after the code has been modified, an error occurs.
error code is that.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IAdminDAO service.AdminService.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IAdminDAO] 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.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
I thought about the cause of the error,
but I think it is because I did not insert the service annotation.
However, there is no typos in any way, and everything is written correctly and errors occur. Is there something I don't know?
Can you tell me what caused this error?
And what about the solution?
Please help me..

Try to change this code of yours:
#Autowired
public AdminService aService;
to this:
#Autowired
public AdminService adminService;
because when you Autowire, he can't see aService on your context that's why he can't create instance of adminService as a default name of your Service bean.
EDIT:
Another thing is you have to implement your interfaces to a concrete class in order to instantiate beans, you can't instantiate interfaces remember, so you need concrete beans to implement what is on your interfaces. Like this:
#Repository
public class IAdminDAOImpl implements IAdminDAO {
//Implementation here
}
#Service
public class AdminServiceImpl implements AdminService {
//Implementation here
}

Related

Spring annotations #NotNull and #Size do not work

I've created a simple page project, which checks a single inputdata field "name" and if it's empty or size is less than 5, it has to show a error-message.
At the moment BindingResult thinks there is no error all the time.
Spring.xml 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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.mvc" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Student class:
package com.mvc;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
#NotNull(message = "IsRequired!")
#Size(min = 5, message = "must be greater than 5!")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller:
package com.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
#Controller
public class StudentController {
#RequestMapping("/")
public String showPage(Model model){
model.addAttribute("student", new Student());
return "index";
}
#RequestMapping("/processForm")
public String processForm(
#Valid #ModelAttribute("student") Student student,
BindingResult theBindingResult) {
if (theBindingResult.hasErrors()) {
return "index";
} else {
return "student-confirm";
}
}
}
If required, i can post web.xml, and jsp pages.
Removed previous version of Tomcat(7.0) and installed latest version.

No mapping found for HTTP request with URI [/LoginApp/displayForm.html] in DispatcherServlet with name 'java4s'

I am facing this error No mapping found for HTTP request with URI [/LoginApp/displayForm.html] in DispatcherServlet with name 'java4s'
Earlier the page was redirecting but now it is not redirecting.
My code is as follows
Java4sController.java
package java4s;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.sql.*;
//import org.h2.jdbcx.JdbcConnectionPool;
//import org.springframework.security.core.context.SecurityContextHolder;
#Controller
public class Java4sController {
HttpSession session;
String uname="",pass="";
Statement stmt;
Connection conn;
#RequestMapping(value="displayForm", method=RequestMethod.GET)
public String helloWorld(UserDetails ud,HttpServletRequest request,HttpServletResponse response) {
return "loginPage";
}
#RequestMapping("/login")
public String loginCheck(#Valid UserDetails userDetails, BindingResult result, ModelMap model,HttpServletRequest request,HttpServletResponse response)throws Exception {
System.out.println("In the login page");
String username=userDetails.getUser();
String password=userDetails.getPassword();
if (result.hasErrors()) {
return "loginPage";
}
try {
Class.forName("org.h2.Driver");
conn = DriverManager.
getConnection("jdbc:h2:file:C:/Users/aaggarwal/test", "sa", "");
// add application code here
if(conn!=null) {
System.out.println("No connection");
}
stmt=conn.createStatement();
String sql="Select * FROM table1 WHERE username='"+username+"' AND password='"+password+"' ";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {
uname=rs.getString("username");
pass=rs.getString("password");
if (result.hasErrors()) {
return "loginPage";
} else if(username.equals(uname)&&password.equals(pass)) {
//session.invalidate();
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma","no-cache");
session = request.getSession(); // create session
session.setAttribute("username", username);
session.setAttribute("password", password);
//String str1=(String)session.getAttribute(username);
model.addAttribute("lfobj", userDetails);
//model.addAttribute(str1);
conn.close();
return "success";
} else {
conn.close();
return "loginPage";
}
}
} finally {
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
} catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return "abcd";
}
#RequestMapping(value="logoutform", method=RequestMethod.GET)
public String helloWorld1(UserDetails ud,HttpServletRequest request,HttpServletResponse response) {
System.out.println("\nabcdef\n");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma","no-cache");
String username=ud.getUser();
// String password=ud.getPassword();
HttpSession session1;
session1=request.getSession(false);
System.out.println("Session :"+session1.getAttribute("username"));
if(session1!=null) {
//session1.removeAttribute(username);
session1.invalidate();
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setPath("/");
response.addCookie(cookie);
}
System.out.println("invalidating session");
//session1.invalidate();
}
return "logoutsuccess";
}
}
java4s-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="java4s" />
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="index"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="props" />
</bean>
</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/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<servlet>
<servlet-name>java4s</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>java4s</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
The error is No mapping found for HTTP request with URI [/LoginApp/displayForm.html] means no mapping for displayForm.html.
Because in controller you have given
#RequestMapping(value="displayForm", method=RequestMethod.GET)
Change that to
#RequestMapping(value="displayForm.html", method=RequestMethod.GET)
Or in web.xml
<servlet-mapping>
<servlet-name>java4s</servlet-name>
<url-pattern>/*.html</url-pattern>
</servlet-mapping>

No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
when I do a test with JUnit, persist method works and I see that my object is inserted, but when I call the method via my Controller doesn't work
here is my Project :
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.2.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-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<!-- <bean id="notification" class="com.app.sqli.notification.NotificationTask" /> -->
<!-- <task:scheduled-tasks> -->
<!-- <task:scheduled ref="notification" method="notifier" cron="*/2 * * * * *"/> -->
<!-- </task:scheduled-tasks> -->
<context:component-scan base-package="com.app.sqli" />
<mvc:annotation-driven />
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.app.sqli.entities" />
<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/sqli" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven />
</beans>
my Model Class:
package com.app.sqli.models;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Collaborateur {
#Id
private int id;
private String nom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
my DAO Class
package com.app.sqli.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.app.sqli.models.Collaborateur;
#Repository
public class CollaborateurDao implements IcollaborateurDao{
#PersistenceContext
private EntityManager em;
#Override
public void addCollaborateur(Collaborateur c) {
em.persist(c);
}
}
My Service Class
package com.app.sqli.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.app.sqli.dao.IcollaborateurDao;
import com.app.sqli.models.Collaborateur;
#Service
#Transactional
public class CollaborateurService implements IcollaborateurService{
#Autowired
private IcollaborateurDao cdao;
#Override
public void addCollaborateur(Collaborateur c) {
cdao.addCollaborateur(c);
}
}
And My Controller
package com.app.sqli.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.app.sqli.models.Collaborateur;
import com.app.sqli.services.IcollaborateurService;
#org.springframework.stereotype.Controller
public class Controller {
#Autowired
private IcollaborateurService cserv;
#RequestMapping(value = "/index")
public String index(Model m) {
System.out.println("insertion ...");
Collaborateur c = new Collaborateur();
c.setId(11);
c.setNom("nom");
cserv.addCollaborateur(c);
return "index";
}
}
thank you #mechkov for your time and help,
My problem is resolved by changing my configuration file, so I have used a Configuration Class with annotations and its works so fine, I still Don't know where the problem was
#Configuration
#ComponentScan(basePackages = "your package")
#EnableTransactionManagement
public class DatabaseConfig {
protected static final String PROPERTY_NAME_DATABASE_DRIVER = "com.mysql.jdbc.Driver";
protected static final String PROPERTY_NAME_DATABASE_PASSWORD = "password";
protected static final String PROPERTY_NAME_DATABASE_URL = "jdbc:mysql://localhost:3306/databasename";
protected static final String PROPERTY_NAME_DATABASE_USERNAME = "login";
private static final String PROPERTY_PACKAGES_TO_SCAN = "where your models are";
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter){
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactoryBean.setPackagesToScan(PROPERTY_PACKAGES_TO_SCAN);
return entityManagerFactoryBean;
}
#Bean
public BasicDataSource dataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(PROPERTY_NAME_DATABASE_DRIVER);
ds.setUrl(PROPERTY_NAME_DATABASE_URL);
ds.setUsername(PROPERTY_NAME_DATABASE_USERNAME);
ds.setPassword(PROPERTY_NAME_DATABASE_PASSWORD);
ds.setInitialSize(5);
return ds;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
//I'm using MySQL5InnoDBDialect to make my tables support foreign keys
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect");
return adapter;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
I do not know if anyone who is reading this (today) has the same case as mine, but I had the same problem. Luckly, I could fix it by simply putting the following in my spring-conf.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
...
xmlns:tx="http://www.springframework.org/schema/tx"
...
xsi:schemaLocation="
...
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="tManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<!-- This does the trick! -->
<tx:annotation-driven transaction-manager="tManager" />
Note: I'm using declarative transactions through annotations. So, if you do, annotating your method with #Transactional can also solve your problem.
REFERENCE:
http://blog.jhades.org/how-does-spring-transactional-really-work/
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/transaction.html
Just to confirm, that adding last bean definition solves this issue !
My config class is as below :
#Configuration
#EnableTransactionManagement
#ComponentScan
public class OFSConfig {
#Bean
public IDAO<FuelStation> getFSService() {
return new FSService();
}
#Bean
public LocalEntityManagerFactoryBean emfBean() {
LocalEntityManagerFactoryBean e = new LocalEntityManagerFactoryBean();
e.setPersistenceUnitName("org.superbapps.db_OWSDB_PU");
return e;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory em) {
return new JpaTransactionManager(em);
}
}
The service itself is as follows :
#Transactional
#Repository
public class FSService implements IDAO<FuelStation> {
#PersistenceContext
private EntityManager EM;
public EntityManager getEM() {
return EM;
}
public void setEM(EntityManager EM) {
this.EM = EM;
}
#Override
public List<FuelStation> getAll() {
return EM.createNamedQuery("FuelStation.findAll")
.getResultList();
}
#Override
public FuelStation getByID(String ID) {
FuelStation fs = (FuelStation) EM.createNamedQuery("FuelStation.findById")
.setParameter("id", ID)
.getSingleResult();
return fs;
}
#Override
public void update(FuelStation entity) {
EM.merge(entity);
}
}

how can i change error's messages in spring?

I'm doing the step by step web app in spring described in here http://docs.spring.io/docs/Spring-MVC-step-by-step/.
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.companyname.springapp.web" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
<%# include file="/WEB-INF/views/include.jsp" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title><fmt:message key="title"/></title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1><fmt:message key="priceincrease.heading"/></h1>
<form:form method="post" commandName="priceIncrease">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%">Increase (%):</td>
<td width="20%">
<form:input path="percentage"/>
</td>
<td width="60%">
<form:errors path="percentage" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Execute">
</form:form>
Home
</body>
</html>
package com.companyname.springapp.service;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PriceIncrease {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Min(0)
#Max(50)
private int percentage;
public void setPercentage(int i) {
percentage = i;
logger.info("Percentage set to " + i);
}
public int getPercentage() {
return percentage;
}
}
package com.companyname.springapp.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.companyname.springapp.service.PriceIncrease;
import com.companyname.springapp.service.ProductManager;
#Controller
#RequestMapping(value="/priceincrease.htm")
public class PriceIncreaseFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
#Autowired
private ProductManager productManager;
#RequestMapping(method = RequestMethod.POST)
public String onSubmit(#Valid PriceIncrease priceIncrease, BindingResult result)
{
if (result.hasErrors()) {
return "priceincrease";
}
int increase = priceIncrease.getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
return "redirect:/hello.htm";
}
#RequestMapping(method = RequestMethod.GET)
protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(15);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
title=SpringApp
heading=Hello :: SpringApp
greeting=Greetings, it is now
priceincrease.heading=Price Increase :: SpringApp
error.not-specified=Percentage not specified!!!
error.too-low=You have to specify a percentage higher than {0}!
error.too-high=Don''t be greedy - you can''t raise prices by more than {0}%!
required=Entry required.
typeMismatch=Invalid data.
typeMismatch.percentage=That is not a number!!!
The problem is I not getting the messages I've defined e.g when I insert 65 in the percentaje field I'm not getting the following message: Don''t be greedy - you can''t raise prices by more than {0}%!. Instead of this I'm getting the default message.
I've deleted the code asociated to the autowired annotation just to make the post shorter.
You must know the application works fine, the problems are in the returned messages.
How can I show the messages that I want?
This post explains in detail how to do validation in spring mvc. Click Here
You just need to implement the Validator here's a simple example...
public class PriceIncreaseValidator implements Validator {
#Override
public boolean supports( Class<?> clazz ) {
return PriceIncrease.class.equals(clazz);
}
#Override
public void validate( Object o, Errors e ) {
PriceIncrease priceIncrease = (PriceIncrease) o;
if( priceIncrease.getPercentage() == 0 ) {
e.rejectValue( "priceIncrease", "error.too-low");
} else if( priceIncrease.getPercentage() >= 50 ) {
e.rejectValue( "priceIncrease", "error.too-high");
}
}
}

Autowired Field is Null

Im have been working on a example for spring MVC + Spring Security + hibernate to make a login page, but now i have come to a problem with a fuel #Autowire that keeps giving me null values. the server doesnt report any errors its just that it doesnt complete the operation.
CustomUSerDetailsService.java
package com.carloscortina.paidosSimple.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import com.carloscortina.paidosSimple.dao.UsuarioDao;
import com.carloscortina.paidosSimple.model.Usuario;
#Service
#Transactional(readOnly=true)
public class CustomUserDetailsService implements UserDetailsService {
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
#Autowired UsuarioDao userDao;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
logger.info(username);
Usuario domainUser = userDao.getUsuario(username);
logger.info(domainUser.getUsername());
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(
domainUser.getUsername(),
domainUser.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(domainUser.getRol().getId()));
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer rol){
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(rol));
return authList;
}
public List<String> getRoles(Integer rol){
List<String> roles = new ArrayList<String>();
if(rol.intValue() == 1){
roles.add("ROLE_DOCTOR");
roles.add("ROLE_ASISTENTE");
}else if (rol.intValue() == 2){
roles.add("ROLE_ASISTENTE");
}
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
Here the field userDao keeps beign null so when i try to use userDao.getUsuario(username) the operation just doesnt continue, it doesn't report an error or similar its just gives me a 404- error
UsuarioDao.xml
package com.carloscortina.paidosSimple.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.carloscortina.paidosSimple.model.Usuario;
#Repository
public class UsuarioDaoImp implements UsuarioDao {
private static final Logger logger = LoggerFactory.getLogger(UsuarioDaoImp.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public Usuario getUsuario(String username) {
logger.debug("probando");
List<Usuario> userList = new ArrayList<Usuario>();
Query query = getCurrentSession().createQuery("from Usuario u where u.Username = :username");
query.setParameter("username", username);
userList = query.list();
if (userList.size() > 0){
return (Usuario) userList.get(0);
}else{
return null;
}
}
}
servlet-context.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"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Enable transaction Manager -->
<tx:annotation-driven/>
<!-- DataSource JNDI -->
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/paidos" resource-ref="true" />
<!-- Session factory -->
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:hibernateProperties-ref="hibernateProperties"
p:packagesToScan="com.carloscortina.paidosSimple.model" />
<!-- Hibernate Properties -->
<util:properties id="hibernateProperties">
<beans:prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">false</beans:prop>
</util:properties>
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.carloscortina.paidosSimple" />
</beans:beans>
I dont know whats missing , so any idea its welcome, thanks in advance.
Edit:
UsuarioDaoImp
package com.carloscortina.paidosSimple.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.carloscortina.paidosSimple.model.Usuario;
#Repository
public class UsuarioDaoImp implements UsuarioDao {
private static final Logger logger = LoggerFactory.getLogger(UsuarioDaoImp.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
#Override
public Usuario getUsuario(String username) {
logger.debug("probando");
List<Usuario> userList = new ArrayList<Usuario>();
Query query = getCurrentSession().createQuery("from Usuario u where u.Username = :username");
query.setParameter("username", username);
userList = query.list();
if (userList.size() > 0){
return (Usuario) userList.get(0);
}else{
return null;
}
}
}
After trying to add a bean with UsuarioDaoImp i got this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioServicioImp': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.carloscortina.paidosSimple.dao.UsuarioDao com.carloscortina.paidosSimple.service.UsuarioServicioImp.usuarioDao; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.carloscortina.paidosSimple.dao.UsuarioDao] is defined: expected single matching bean but found 2: usuarioDaoImp,userDao
UsuarioServiceImp
package com.carloscortina.paidosSimple.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.carloscortina.paidosSimple.dao.UsuarioDao;
import com.carloscortina.paidosSimple.model.Usuario;
#Service
#Transactional
public class UsuarioServicioImp implements UsuarioService{
#Autowired
private UsuarioDao usuarioDao;
#Override
public Usuario getUsuario(String username) {
return usuarioDao.getUsuario(username);
}
}
i think I'm short in knowledge about the subject, that why i was following an example but i ended with this, so my apologise if I'm not giving the information correctly or if im misunderstanding concepts.
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:security="http://www.springframework.org/schema/security"
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"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<beans:bean class="com.carloscortina.paidosSimple.service.CustomUserDetailsService" id="customUserDetailsService"></beans:bean>
<security:http auto-config="true">
<security:intercept-url pattern="/sec/moderation.html" access="ROLE_ASISTENTE" />
<security:intercept-url pattern="/admin/*" access="ROLE_DOCTOR" />
<security:form-login login-page="/user-login.html"
default-target-url="/success-login.html"
authentication-failure-url="/error-login.html" />
<security:logout logout-success-url="/index.html" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
<security:password-encoder hash="plaintext" />
</security:authentication-provider>
</security:authentication-manager>
</beans:beans>
How are you accessing CustomUSerDetailsService class ? I hope you haven't added this class as bean in security config file or any other spring config?
Editted:
Your service bean is annotated with #service and you have also declared it in xml, spring has created two service beans one based on #service annotation (fully populated as its autowried) and second using the xml config (in which I assume you haven't injected dao dependency explicitly), so the second one doesnt have dao object set. As you are using the bean name of the service bean declared in your security config, you are getting userDao as null on debug.
Either comment the explicit bean definition in security xml, use ref="customUSerDetailsService" directly as #service annotation already added a bean with this name in spring context.
i.e. comment/remove this line in your security config and every thing should work.
<beans:bean class="com.carloscortina.paidosSimple.service.CustomUserDetailsService" id="customUserDetailsService"></beans:bean>
When you annotate a bean with #component/#service spring adds a bean with name equals to short classname(first letter lower case), so bean with name "customUserDetailsService" already exists, defining it explicitly in xml is overriding it.
Or declare all the bean definitions (including there dependencies) explicitly it xml config
Add the dao package to the component scan
<context:component-scan base-package="com.carloscortina.paidosSimple, com.carloscortina.paidosSimple.dao" />

Resources