简体   繁体   中英

Set password runtime with Hibernate / JPA

I have a web app with a db connection properties defined in persistence.xml.

I am using contained manager persistence with the entity manager injected using @PersistenceContext.

Today the password to the DB is in the persistence.xml file, but I would rather set it runtime (ask the user for it).

I am able to create a new EntityManager with the password runtime, but how can I "override" the injected one?

Any other good ideas/approaches?

Yes, this is a bit worried with configuring the profiles for different environments.

Though it wont suffice your "runtime" setting of the password and replace the object, but it would be maintained as the spring bean profiles.

Something like this;

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }

}

Lets say you want to load the profile for production ?

You have to define another profile with @Profile("production") and load the properties file from the classpath location.

With spring boot, you can activate your profile as

SPRING_PROFILES_ACTIVE=production mvn spring-boot:run

This can make you to change the password and bounce the server whenever it is required. Anyways as you change the password, the connection needs a reboot. So ideally this should make the job easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM