• properties文件


    Java知识点总结:想看的可以从这里进入

    12、properties文件


    12.1、properties文件

    后缀是 .properties的一种文件,他和和yml文件,json格式一样都是属性文件,内部以key=value格式存储内容,一般以这种文件设置一些参数,使代码更加灵活(比方说:数据库文件等等都是在properties文件中),使用这种文件在不同环境中只需要更改配置文件即可。

    • 键值对格式存储数据
    • “ = ” 后面,值前面的空格,会自动忽略掉。
    • 值后面的空格,不会忽略。
    • “ = ” 后面的双引号不会忽略。
    • “ # ”号后面内容,为注释,

    比如在properties文件中编写数据库的连接信息

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    jdbc.username=root
    jdbc.password=密码
    
    • 1
    • 2
    • 3
    • 4

    12.2、Java 类获取

    12.2.1、Properties

    在Java中可以用 java.util.Properties 类读取 properties文件中的信息

    • load ( InputStream inStream) :读取指定文件中的键值对内容
    • getProperty ( String key) :通过参数 key ,得到 key 所对应的 value。
    • setProperty ( String key, String value) :调用Hashtable的方法put ,来设置 键 - 值对。
    • keySet ( ) :拿到properties中所有的key。
    • clear ( ) :清除所有装载的 键 - 值对。
    public class PropertiesTest {
        @Test
        public  void  propertiesTest() throws IOException {
            Properties properties = new Properties();
            // 读取指定文件中的键值对内容,需要再src内(也可以使用流读取,用流读取时,properties可以在任意位置)
            properties.load(PropertiesTest.class.getResourceAsStream("/database.properties"));
            //根据key获取value
            String driver = properties.getProperty("jdbc.driver");
            String username = properties.getProperty("jdbc.username");
            System.out.println(driver);
            System.out.println(username);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    image-20220911175631293
    12.2.2、ResourceBundle
    @Test
    public  void  ResourceBundleTest() throws IOException {
        //这种方式不用写 properties 文件后缀
        ResourceBundle database = ResourceBundle.getBundle("database");
        String driver = database.getString("jdbc.driver");
        String username = database.getString("jdbc.username");
        System.out.println(driver);
        System.out.println(username);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    image-20230329211130056

    12.3、XML文件获取

    通过 context:property-placeholder 标签来加载properties 文件。

    • 我们可以通过 properties 文件配置数据库连接 或对象的属性值

      # 数据库连接信息
      jdbc.driver=com.mysql.cj.jdbc.Driver
      jdbc.url=jdbc:mysql://localhost:3306/库名?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
      jdbc.username=root
      jdbc.password=密码
      # User的属性值
      userId=1
      name=properties
      pass=123456
      deleted=true
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
    • 在Spring的XML文件中加载properties

      
      <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.xsd
                  http://www.springframework.org/schema/context
                  https://www.springframework.org/schema/context/spring-context.xsd">
      
          
          <context:property-placeholder location="classpath:database.properties"/>
          
          <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="${jdbc.driver}"/>
              <property name="url" value="${jdbc.url}"/>
              <property name="username" value="${jdbc.username}"/>
              <property name="password" value="${jdbc.password}"/>
          bean>
          
           <bean id="propertiesTestUser" class="com.yu.spring.entiy.User">
              <property name="userId" value="${userId}"/>
              <property name="username" value="${name}"/>
              <property name="password" value="${pass}"/>
              <property name="deleted" value="${deleted}"/>
          bean>
      
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
    • 测试

      image-20230329212715732

    12.4、注解获取

    spring提供了 @PropertySource(“classpath:文件名”)注解来加载properties文件中的配置

    1. name:名称
    2. value:{“classpath:文件名”,…}:可配置多个文件
    3. ignoreResourceNotFound:默认为false,如果找不到文件是否忽略,不设置,找不到会抛出异常
    @Configuration
    @PropertySource(value = {"classpath:database.properties"},ignoreResourceNotFound = true)
    public class SpringConfig {
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在配置文件上添加了SpringConfig 注解后,就可以通过配置文件获取 properties文件中的内容了

    image-20230329213144911

    在加载完properties文件后,可以通过@value、@Bean设置成相应的对象

    @Configuration
    @PropertySource(value = {"classpath:database.properties"},ignoreResourceNotFound=true)
    public class PropertiesConfiguration {
        @Value("${jdbc.driver}")
        private String driverClassName;
    
        @Value("${jdbc.url}")
        private String url;
    
        @Value("${jdbc.username}")
        private String username;
    
        @Value("${jdbc.password}")
        private String password;
    
        //设置数据库连接
        @Bean
        public DataSource annotationPropertiesDataSource() throws Exception {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
        @Value("${userId}")
        private int userId;
    
        @Value("${name}")
        private String name;
    
        @Value("${pass}")
        private String pass;
    
        @Value("${deleted}")
        private boolean deleted;
        //设置User对象
        @Bean
        public User annotationPropertiesUser() throws Exception {
            User user = new User();
            user.setUserId(userId)
                    .setUsername(name)
                    .setPassword(pass)
                    .setDeleted(deleted);
            return user;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    image-20230329213932795
  • 相关阅读:
    [深度学习]基于C++和onnxruntime部署yolov10的onnx模型
    springboot中如何进行业务层测试事务回滚
    vue+elementui网上线上教学平台python+java
    Python中的@dataclass装饰器
    python_循环
    最近opencv又报了啥错(一)
    乘方(pow) CSP-J2022
    库存管理“智慧官”上线!北京电信基于飞桨打造主动型库存决策分析系统
    【动手学深度学习】--长短期记忆网络LSTM
    I2C接口及时序
  • 原文地址:https://blog.csdn.net/yuandfeng/article/details/126807843