当前位置: 首页 > 知识库问答 >
问题:

使用application.properties文件的Spring

宗政浩慨
2023-03-14

Fof简单方便,这里引用我的代码。

第一个类,学生(存储在db中的实体):

package com.tutorialspoint;

public class Student 
{
       private Integer age;
       private String name;
       private Integer id;

       public void setAge(Integer age) 
       {
          this.age = age;
       }

       public Integer getAge() 
       {
          return age;
       }

       public void setName(String name) 
       {
          this.name = name;
       }

       public String getName() 
       {
          return name;
       }

       public void setId(Integer id) 
       {
          this.id = id;
       }

       public Integer getId() 
       {
          return id;
       }
    }

接口,StudentDAO(用于DAO逻辑):

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO 
{
   /** 
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);

   /** 
      * This is the method to be used to create
      * a record in the Student table.
   */
   public void create(String name, Integer age);

   /** 
      * This is the method to be used to list down
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public Student getStudent(Integer id);

   /** 
      * This is the method to be used to list down
      * all the records from the Student table.
   */
   public List<Student> listStudents();

   /** 
      * This is the method to be used to delete
      * a record from the Student table corresponding
      * to a passed student id.
   */
   public void delete(Integer id);

   /** 
      * This is the method to be used to update
      * a record into the Student table.
   */
   public void update(Integer id, Integer age);
}
package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO 
{
   private DataSource dataSource;
   private JdbcTemplate jdbcTemplateObject;

   public void setDataSource(DataSource dataSource) 
   {
      this.dataSource = dataSource;
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }

   public void create(String name, Integer age) 
   {
      String SQL = "insert into Student (name, age) values (?, ?)";
      jdbcTemplateObject.update( SQL, name, age);
      System.out.println("Created Record Name = " + name + " Age = " + age);
      return;
   }

   public Student getStudent(Integer id) 
   {
      String SQL = "select * from Student where id = ?";
      Student student = jdbcTemplateObject.queryForObject(SQL, 
         new Object[]{id}, new StudentMapper());

      return student;
   }

   public List<Student> listStudents() 
   {
      String SQL = "select * from Student";
      List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
      return students;
   }

   public void delete(Integer id) 
   {
      String SQL = "delete from Student where id = ?";
      jdbcTemplateObject.update(SQL, id);
      System.out.println("Deleted Record with ID = " + id );
      return;
   }

   public void update(Integer id, Integer age)
   {
      String SQL = "update Student set age = ? where id = ?";
      jdbcTemplateObject.update(SQL, age, id);
      System.out.println("Updated Record with ID = " + id );
      return;
   }
}
package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMapper implements RowMapper<Student> 
{
   public Student mapRow(ResultSet rs, int rowNum) throws SQLException 
   {
      Student student = new Student();
      student.setId(rs.getInt("id"));
      student.setName(rs.getString("name"));
      student.setAge(rs.getInt("age"));

      return student;
   }
}

最后一个类,MainApp(运行应用程序):

  package com.tutorialspoint;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.StudentJDBCTemplate;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      StudentJDBCTemplate studentJDBCTemplate = 
         (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

      System.out.println("------Records Creation--------" );
      studentJDBCTemplate.create("Zara", 11);
      studentJDBCTemplate.create("Nuha", 2);
      studentJDBCTemplate.create("Ayan", 15);

      System.out.println("------Listing Multiple Records--------" );
      List<Student> students = studentJDBCTemplate.listStudents();

      for (Student record : students) {
         System.out.print("ID : " + record.getId() );
         System.out.print(", Name : " + record.getName() );
         System.out.println(", Age : " + record.getAge());
      }

      System.out.println("----Updating Record with ID = 2 -----" );
      studentJDBCTemplate.update(2, 20);

      System.out.println("----Listing Record with ID = 2 -----" );
      Student student = studentJDBCTemplate.getStudent(2);
      System.out.print("ID : " + student.getId() );
      System.out.print(", Name : " + student.getName() );
      System.out.println(", Age : " + student.getAge());
   }
}

最后,配置数据库连接的Beans文件

<?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 ">

   <!-- Initialization for data source -->
   <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/springtraining"/>
      <property name = "username" value = "***"/>
      <property name = "password" value = "***"/>
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate" 
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource" />    
   </bean>

</beans>

该教程非常清楚,如果我尝试它,将会有一个完美的执行,没有错误,MySQL Db被正确地更新。

spring.datasource.driver-class-name=com.mysql.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:3306/springtraining spring.datasource.username=*spring.datasource.password=*

如果我不想使用RowMapper类,那么使用spring提供的BeanPropertyRowMapper是正确的吗?

如果没有bean文件(在本例中,如果我使用application.properties,我就不需要它了),我如何在MainApp中替换以下行:

ApplicationContext context=new ClassPathXmlApplicationContext(“beans.xml”);

  StudentJDBCTemplate studentJDBCTemplate = 
     (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

并使这些应用程序可执行?

共有1个答案

秦炜
2023-03-14

首先,我建议您学习如何在没有application.properties文件的情况下执行此操作。我们生活在21世纪,spring-boot允许我们将jdbcdatasource声明为@bean,并在MySpringBootApplication类中使用数据库凭据。看这里怎么做

其次,我建议不要使用jdbctemplate,除非您没有时间。记住我的话,如果碰巧调试--那将是噩梦。因此,尝试使用添加spring配置的纯Jdbc。

如何做的示例:

StudentDAO接口

    public interface StundentDAO {

    void addStudent(String name, String surname);

    List<Student> findStudents();
}

JdbcStudentDAO实现

    @Repository
    public class JdbcStudentDAO implements StudentDAO {

    //[IMPORTANT] import javax.sql.datasource package (?)
    private Datasource datasource;

    @Autowire
    public JdbcStudentDAO(Datasource datasource) {
        this.datasource = datasource;
    }

    @Override
    public void addStudent(String name, String surname) {
        String query = "INSERT INTO Students VALUES (?,?)";
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                statement.setString(1, name);
                statement.setString(2, surname);
                statement.executeUpdate();
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
    }

    @Override
    public List<Student> findStudents() {
        String query = "SELECT * FROM Students";
        Student student = null; //will be used soon as DTO
        List<Student> listOfStudents = null;
        try(Connection connection = datasource.getConnection()) {
            try(PreparedStatement statement = connection.preparedStatement(query)) {
                try(ResultSet rs = statement.executeQuery()) {
                    listOfStudents = new ArrayList<>();
                    while(rs.next()) {
                        student = new Student(
                            rs.getString("name");
                            rs.getString("surname");
                        );
                    }
                    listOfStudents.add(student);
                }
            }
        } catch(SQLException e) {
            e.printStacktrace();
        }
        return listOfStudents;
    }
} 
 类似资料:
  • 我正在尝试在Spring Boot项目中加载应用程序属性进行测试。我也在使用@DataJpaTest注释。许多人建议使用@TestProperty tySource注释与@datajpaTest的组合,但它不是加载属性。如果我使用@SpringBooTest,它就是加载属性。 我的应用程序属性文件位于主/资源/文件夹中。如果我使用,它正在工作,但我有 这未能使用Spring启动测试进行自动配置。我

  • 问题内容: 我想使用带有以下条目的application.properties文件设置配置文件: 如何在我的context.xml文件中设置spring.profiles.active?init-param仅在web.xml上下文中有效。 问题答案: 有几种更改活动配置文件的方法,这些方法都不直接取自属性文件。 您可以像在问题中一样使用。 您可以在应用程序启动时提供系统参数 你可以得到从你和编程方

  • 我想在application.properties中定义高级文件日志记录,以方便利用我的log4j2.xml文件配置。我的log4j2配置本身运行良好,但是我希望控制日志级别以及application.properties文件中的日志文件和路径信息。我在应用程序的pom文件中有spring-boot-starter-log4j2依赖项。 在log4j2.xml中,我有一个属性 ,其中LOG-DIR

  • 我有一个非常简单的Spring Boot应用程序,下面详细介绍了类。 和src/main/java/sample/com/example/maincontroller.java

  • 我有一个带有一个测试类dbtest的maven模块。运行测试时,不会提取属性文件application.properties。DvsTestDbConfig中的行system.out.println显示的是{database.test},而不是qqqqqqqqq(暂时为虚拟值)。知道为什么spring找不到属性文件吗? DBTest DVSTestDBConfig

  • 我试图用Spring Boot配置DynamoDb客户机,并将我的endpoint和配置信息放置在我的resources/application.properties文件中。但Spring Boot似乎并没有拾起这些属性。它确实会拾取我存储在同一文件中的“server.default”键,因此它肯定会识别文件本身。 下面是我的application.properties文件和我试图将属性加载到(D