【问题标题】:Can i load username and password by file in spring boot + hibernate?我可以在spring boot + hibernate中按文件加载用户名和密码吗?
【发布时间】:2019-02-01 09:57:03
【问题描述】:

我想使用 spring boot、oracle db 和 hibernate。我想通过两个文件(user.txt 和 password.txt)为 oracle db 模式加载用户名和密码。我可以使用休眠吗?我不知道如何从 application.properties 文件中加载用户名和密码以进行休眠。 (spring.datasource.username = 从 user.txt 加载, spring.datasource.password = 从 password.txt 加载)。用户和密码在文件中加密。

有人知道我是怎么做到的吗?

【问题讨论】:

标签: java spring oracle hibernate spring-boot


【解决方案1】:

有几种方法可以做到这一点,但使用属性文件,而不是 txt 文件。如果您愿意采用这种方法,您的选择是:

  1. 您的配置类中的@PorpertySources。一个例子是

    @PropertySources({
            @PropertySource("/user.properties"),
            @PropertySource("/password.properties")
    }). 
    @Configuration
    public configClass{
        @Value("{db.user}")
        private String user;
        @Value("{db.password}")
        private String password;
        ...
    }
    

db.user 和 db.password 必须在您的配置文件中定义。使用这些数据,您可以定义数据源(您还需要连接 url)

  1. 如果您使用的是休眠配置文件,您可以在此答案中找到一个示例: How to read database configuration parameter using properties file in hibernate

【讨论】:

  • 谢谢,但是用户和密码在文件中是加密的,我需要两个不同的用户和密码文件。
  • 在这种情况下,我想您将需要创建您的自定义正确源。您必须创建一个扩展 PropertySource 的类并实现方法 public Object getProperty(String name)。在本课程中,您将能够访问加密文件、解密它们并解析它们以检索您需要的 de 属性。您还需要在环境中注册属性源,执行 env.getPropertySources().addFirst(new YourCustomPropertySource(param));此处示例:stackoverflow.com/questions/14416005/…
  • 谢谢,我会试试这个!
  • 希望对您有所帮助。 :)
【解决方案2】:

只需在 .jar 之外添加另一个 application.properties,其中包含数据库信息。请参阅 spring 文档 -> https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

将您的 application.properties 放在打包的 jar 文件之外。 Spring Boot 将在同一目录中查找属性,并且可以像文件在类路径中一样访问值。

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 2021-12-02
    • 2022-12-25
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多