DEV Community 👩‍💻👨‍💻

Cover image for Hide credentials in spring boot
Amit Tiwary
Amit Tiwary

Posted on

Hide credentials in spring boot

Spring boot make it easy to create spring applications. It makes it easier and faster to set up, configure and run the web application. When I was working on one of the projects, I was required to use some credentials. But I can't use it directly in the code. It should be hidden and still accessible in the code. We know that we can add the variable in the file and then use it in the java code. But I was not ablw to find how can add the env variable in a file and then access it in the file. If variables can be added in a file and accessed in the then the file can be included in the gitignore, and code can be pushed to github and shared with others without exposing the credential.

So I did research and find out that we can import a file in the and use the variables. We are going to use the file to save the credentials. Create a file. I created this file in the resources folder, so that I can easily access in the

folder to save the
Add some credentials in the file like

Enter fullscreen mode Exit fullscreen mode

These are the secret info and can't be shared with everyone. But it is required to connect with the database server or to use the google service.

Now to access these variables in our java file, we have to import these variables in the file. Import the file so that we can get these variables in the file.

sprint.config.import =
spring.datasource.username = DB_USER
Enter fullscreen mode Exit fullscreen mode file is in the same folder with the so it can be imported directly using the file name. We are telling the code to use the config from the import file i.e from

Now to make sure that the credentials is not commited and pushed to github, we have to make sure that file is included in .gitignore.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Git push

Stop by this week's meme thread!