I am trying to run a test function to get the name and id of my bean from the config file. I have tried everything I can think of up until now and no luck. I get about 40 lines of errors that I have no idea how to read. I am certain it is something simple but I am just not connecting the dots. How can I fix this?
package com.intraedge.spring.springcore;
class Employee {
private int id;
private String name;
// public int getId(int args) {
// id = args;
// return id;
// }
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.intraedge.spring.springcore;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
Employee emp = (Employee)ctx.getBean("emp");
System.out.println("Name: "+emp.getName(name.value));
// System.out.println("Id: "+emp.getId(3));
}
}
<?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:p="http://www.springframework.org/schema/p"
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">
<bean name="emp" class="com.intraedge.spring.springcore.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Casandra</value>
</property>
</bean>
</beans>
After updating the namespaces like suggested, there was a new error relating to the getter/setter of the bean ID. I fixed it by adding in the proper getter/setter functions and removing any arguments from the function calls.
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
I want to learn Spring, so I write simple java CRUD app. But from the begining have errors org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController'" and org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao' for my servlet. I was looking some solutions, but nothing works.
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Employer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Employer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Employer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.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.javatpoint"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Employers"></property>
<property name="username" value="root"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.EmpDao">
<property name="jdbcTemplate" ref="jt"></property>
</bean>
</beans>
EmpController.java
package com.javatpoint;
import java.util.List;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
#RequestMapping("/empform")
public ModelAndView show() {
return new ModelAndView("empform", "command", new Emp());
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp")Emp emp) {
empDao.save(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp() {
List<Emp> list = empDao.getEmployees();
return new ModelAndView("viewemp", "list", list);
}
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable("id")int id) {
Emp emp = empDao.getById(id);
return new ModelAndView("empeditform", "command", emp);
}
#RequestMapping(value="editsave", method=RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp")Emp emp) {
empDao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/delete")
public ModelAndView delete(#ModelAttribute("emp")Emp emp) {
empDao.delete(emp);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class EmpDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Emp.java
package com.javatpoint;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
The main problem is that you're trying to autowire an EmpDao to your controller without havin an EmpDao bean.
In order to make EmpDao a bean you should annotate the EmpDao class with #Component , #Service or #Repository:
#Service
public class EmpDao {
#Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Remember, you can only inject (or autowire) other beans into your beans.
In spring, the application creates it's own beans (either as singletons, or a 'new' instance anytime you need it.)
EmpController for example is annotated with #Controller to tell spring exactly that- this is a controller, as the application starts up, please create a new instance of this bean, so I can use it.
However, as spring tries to create this bean, it also populates it's variables.
#Autowired on the empDao variable means roughly: "you should already have built an instance of the class empDao, so please, let me have here a reference to it(empDao) so I can call it from this class(empController)"
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
But it seems empDao itself is not configured properly- no annotation to let spring know it should create an instance of it while starting up.
try the following 2 changes:
#Service
public class EmpDao {
and
#Entity
public class Emp {
I was doing some #Autowired annotations in my code where I stumbled upon a doubt. I am getting the name as John even though I have not injected the Employee bean in GetName.java. The bean was getting injected even though I was not autowiring it using any annotation. Is there some specific prerequisite need to be kept in mind while using constructors ?
Employee.Java
package com.sample.employee;
public class Employee {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
GetName.java
package com.sample.salary;
import org.springframework.beans.factory.annotation.Autowired;
import com.sample.employee.Employee;
public class GetName {
// #Autowired
public Employee emp;
// #Autowired
public GetName(Employee emp) {
this.emp = emp;
}
public void displayName() {
System.out.println(emp.getName()); //prints John
}
}
spring.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"
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"
xmlns:context="http://www.springframework.org/schema/context">
<context:annotation-config />
<!-- <context:component-scan base-package="com.sample.employee"/> -->
<bean id="empl" class="com.sample.employee.Employee">
<property name="name" value="John" />
</bean>
<bean id="GetNames" class="com.sample.salary.GetName"/>
</beans>
MainClass.java
package com.sample.employee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sample.salary.SalaryCalculator;
public class MainCLass {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
GetName cal = (GetName) context.getBean("GetNames");
cal.displayName();
}
}
Am I missing out something?
If there is only one Constructor for a Bean, Spring will do constructor injection and the #Autowired annotation can be omitted.
See https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html
This feature was added with one of the more recent versions.
I want to check size validation for studentHobby object and i am using #Size annotation and Using #valid annotation.
I am providing less than the value defined in #Size annotation but still I am getting the result instead of error.
I tried things but didn't come with solutions.
StudentAdmissionController.java
package com.diwakar;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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;
#Controller
public class StudentAdmissionController {
#InitBinder
public void initBinder(WebDataBinder binder) {
//binder.setDisallowedFields(new String[] {"studentMobile"});
//SimpleDateFormat date = new SimpleDateFormat("dd**MM**yyyy");
//binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(date, false));
binder.registerCustomEditor(String.class, "studentName", new StudentNameEditor());
}
#RequestMapping(value="/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#RequestMapping(value="/submitForm", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("st1") Student st1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#ModelAttribute
public void addCommonMessage(Model model) {
model.addAttribute("headerMessage", "Diwakar College of Engineering.!!");
}
Student.java
package com.diwakar;
import java.util.ArrayList;
import java.util.Date;
import javax.validation.constraints.Size;
public class Student {
private String studentName;
#Size(min=3, max=10)
private String studentHobby;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
public Long getStudentMobile() {
return studentMobile;
}
public void setStudentMobile(Long studentMobile) {
this.studentMobile = studentMobile;
}
public Date getStudentDOB() {
return studentDOB;
}
public void setStudentDOB(Date studentDOB) {
this.studentDOB = studentDOB;
}
public ArrayList<String> getStudentSkills() {
return studentSkills;
}
public void setStudentSkills(ArrayList<String> studentSkills) {
this.studentSkills = studentSkills;
}
public Address getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
spring-dispatcher-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:mvc="http://www.springframework.org/schema/mvc"
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.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-3.0.xsd">
<!-- <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/welcome.html" class="com.diwakar.HelloController" /> -->
<context:component-scan base-package="com.diwakar" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Here is my admission page even though i am providing one one character it is giving me submit form instead of error.
admission.html Page
This submit form i am getting after submitting value with 1 character.
submitForm
package com.bpp.beans;
public class EmpBean {
String name;
String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void initempbean()
{
System.out.println("inside initempbean");
}
public void destroyempbean()
{
System.out.println("inside destroyempbean");
}
}
package com.bpp.beans;
public class Person {
String name;
String id;
EmpBean empBean;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public EmpBean getEmpBean() {
return empBean;
}
public void setEmpBean(EmpBean empBean) {
this.empBean = empBean;
}
public void initperson()
{
System.out.println("inside init personnnnnnn");
}
public void destroyperson()
{
System.out.println("inside destroy personnnn");
}
}
package com.bpp.beans;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class EmpPostProcessor implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("inside bean pp after initialization");
return null;
}
#Override
public Object postProcessBeforeInitialization(Object bean, String arg1)
throws BeansException {
System.out.println("inside bean pp before initialization");
return null;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:c="http://www.springframework.org/schema/c"
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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean class="com.bpp.beans.EmpPostProcessor"/>
<bean id="emp" class="com.bpp.beans.EmpBean" init-method="initempbean" destroy-method="destroyempbean">
<property name="name" value="sanjay"/>
<property name="id" value="44"/>
</bean>
<bean id="person" class="com.bpp.beans.Person" init-method="initperson" destroy-method="destroyperson">
<property name="name" value="sanju"/>
<property name="id" value="77"/>
<property name="empBean" ref="emp"/>
</bean>
</beans>
package com.bpp.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bpp.beans.Person;
public class BppMain {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("com/bpp/commons/application-context.xml");
Person obj=context.getBean("person",Person.class);
System.out.println("the value of name is:"+obj.getName());
}
}
The exception is null pointer exception,while creating emp bean
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emp' defined in class path resource [com/bpp/commons/application-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.bpp.main.BppMain.main(BppMain.java:12)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 12 more
In the Spring doc is written for postProcessAfterInitialization and postProcessBeforeInitialization :
Returns:
the bean instance to use, either the original or a wrapped one
Since you do nothing in these methods you should return the Object passed as a parameter, which is the instance of the bean.