BeanLifeCycle不使用java代码

时间:2016-08-02 13:04:46

标签: java xml spring

我正在创建一个示例BeanLifeCycle,其中包含一个简单的连接任务        到数据库并将记录插入其中。当我编写ClientApp.java时        正在回归很多错误。我已经添加了与弹簧相关的JAR和
       我是否需要添加任何与Java相关的额外JARS。

package beans;

 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;

 import org.springframework.beans.factory.DisposableBean;
 import org.springframework.beans.factory.InitializingBean;

 public class Test implements InitializingBean, DisposableBean
  {
     private String driver,url,username,pwd;
     private Connection con;
     public void setDriver(String driver) {
     this.driver = driver;
  }
  public void setUrl(String url) {
 this.url = url;
  }
    public void setUsername(String username) {
     this.username = username;
   }
    public void setPwd(String pwd) {
    this.pwd = pwd;
   }
   @Override
      public void afterPropertiesSet() throws Exception {
    Class.forName(driver);
      con=DriverManager.getConnection(url, username,pwd);

  }
      public void save(int id,String name, String email,String address)
      throws Exception
      {
     PreparedStatement ps=con.prepareStatement("insert into student    
        values(?,?,?,?)");
ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, email);
ps.setString(4, address);

      @Override
public void destroy() throws Exception {
    // TODO Auto-generated method stub
        con.close();
          System.out.println("connection closed");
}
  }

以下程序是ClientApp.java,其中存在大量错误    从阻塞直到切换块生成。

package beans;

    import java.util.Scanner;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.support.
       ClassPathXmlApplicationContext;
   import beans.Test;

    public class ClientApp 
    {
public static void main(String[] args) throws Exception{
    ConfigurableApplicationContext context=new  
       ClassPathXmlApplicationContext("spring.xml");
    while(true)
{
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter 1 for save and 2 for exit");
        int i=sc.nextInt();
        swtich(i)
        {
            case 1: Test t=(Test)context.getBean("t");
            System.out.println("Enter id");
            int id=sc.nextInt();
            System.out.println("Enter Name");
            String name=sc.next();
            System.out.println("Enter Email");
            String email=sc.next();
            System.out.println("Enter Address");
            String address=sc.next();
            t.save(id, name, email, address);
            break;
        default:
            cap.close();
            break;

        }
    }

   }
    }



  Please help me with this task to execute. What other JARs do I need to 
add to connect to database and insert the records into it

   This is the 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-3.0.xsd">
     <bean id="t" class="beans.Test">
     <property name="driver" value="com.mysql.jdbc.Driver"/>
     <property name="url" value="jdbc:mysql://localhost/loginuser"/>
      <property name="username" value="root"/>
      <property name="pwd" value="root"/>
     </bean>
   </beans>

错误是

   WARNING: Exception encountered during context initialization -  
   cancelling refresh attempt:   
   org.springframework.beans.factory.BeanCreationException: Error creating 
   bean with name 't' defined in class path resource [spring.xml]: 
   Invocation of init method failed; nested exception is 
   java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

   Exception in thread "main" 
   org.springframework.beans.factory.BeanCreationException: Error creating 
   bean with name 't' defined in class path resource [spring.xml]: 
   Invocation of init method failed; nested exception is 
   java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.springframework.beans.factory.support.
   AbstractAutowireCapableBeanFactory.initializeBean
   (AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.
   AbstractAutowireCapableBeanFactory.doCreateBean
   (AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.
   AbstractAutowireCapableBeanFactory.createBean 
   (AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.
    AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.
    DefaultSingletonBeanRegistry.getSingleton

    (DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.
    AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.
    AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.
    DefaultListableBeanFactory.preInstantiateSingletons 
    (DefaultListableBeanFactory.java:772)
at org.springframework.context.support.
    AbstractApplicationContext.finishBeanFactoryInitialization
    (AbstractApplicationContext.java:839)
at org.springframework.context.support.
    AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.
    ClassPathXmlApplicationContext.<init>
    (ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.
    ClassPathXmlApplicationContext.<init>
    (ClassPathXmlApplicationContext.java:83)
at beans.ClientApp.main(ClientApp.java:12)
    Caused by: java.lang.ClassNotFoundException: 
    com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at beans.Test.afterPropertiesSet(Test.java:28)
at org.springframework.beans.factory.support.
    AbstractAutowireCapableBeanFactory.invokeInitMethods  
    (AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.
    AbstractAutowireCapableBeanFactory.initializeBean
   (AbstractAutowireCapableBeanFactory.java:1574)
... 12 more

2 个答案:

答案 0 :(得分:0)

重新格式化您的ClienApp.java代码,如下所示。

import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ClientApp 
{
    public static void main(String[] args) throws Exception{
        ConfigurableApplicationContext context=new  
                    ClassPathXmlApplicationContext("spring.xml");

        while(true)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter 1 for save and 2 for exit");
            int i = sc.nextInt();
            switch(i){
                case 1: Test t = (Test)context.getBean("t");
                        System.out.println("Enter ID");
                        int id = sc.nextInt();
                        System.out.println("Enter Name");
                        String name=sc.next();
                        System.out.println("Enter Email");
                        String email=sc.next();
                        System.out.println("Enter Address");
                        String address=sc.next();
                        t.save(id, name, email, address);
                        break;
                default:
                        cap.close();
                        break;
            }
        }

    }
}

同样 cap 对象未在ClienApp中定义,因此也定义了。

编写代码时一定要注意标签和间距。

答案 1 :(得分:0)

您还没有在PreparedStatement对象上调用executeUpdate()方法。请按照以下步骤放置代码以获得所需的结果。

PreparedStatement ps = con.prepareStatement("insert into student   values(?,?,?,?)");

ps.setInt(1, id);
ps.setString(2, name);
ps.setString(3, email);
ps.setString(4, address);

ps.executeUpdate();