I wrote the way to use values of properties, written in application.properties, in Spring.
In Spring, with annotation @Value
, you can use the property values.
Sample Code
Make it available to use the AWS access key value written in properties file.
Of course you can write the code in the controller, but creating the class that has property value is smart. The following code is written in Kotlin.
1 2 3 4 |
## AWS S3 my.s3.bucket_name=bucket-name my.s3.access_key=ABCDEFGHIJKLMN my.s3.access_secret=THIS/IS/ACCESS/SECRET |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.example.sample.config import com.amazonaws.auth.AWSCredentials import com.amazonaws.auth.BasicAWSCredentials import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component @Configuration open class AwsConfig { @Value("${my.s3.bucket_name}") lateinit var bucketName: String @Value("${my.s3.access_key}") lateinit var accessKey: String @Value("${my.s3.access_secret}") lateinit var accessSecret: String val credentials: AWSCredentials get() = BasicAWSCredentials(accessKey, accessSecret) } |
Pass the @Value
annotation, the key value in properties. When I create my own key and value in properties file, I start the key name with “my” to differentiate it from conflicting with one already used in libraries, in most case.
This scheme can be useful when you should use value according to the system environment, like production or development.
Above AwsConfig
class has @Configuration
annotation. @Component
annotation works in the same way.
How to Use Config Class
Then, here’s a sample code using AwsConfig
above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@Component open class AwsS3Gateway { @Autowired lateinit var awsConfig: AwsConfig var s3ClientCache: AmazonS3Client? = null private fun getS3Client(): AmazonS3Client { // ToDo; S3Client Session Management if (s3ClientCache == null) s3ClientCache = generateS3Client() return s3ClientCache!! } private fun generateS3Client(): AmazonS3Client { return AmazonS3Client(awsConfig.credentials) } // ... } |
Owing to @Autowired
annotation, Spring assigns awsConfig
Configration class instance automatically.