{"id":195,"date":"2024-06-05T23:11:08","date_gmt":"2024-06-06T02:11:08","guid":{"rendered":"https:\/\/springmasteryhub.com\/?p=195"},"modified":"2024-06-05T23:11:08","modified_gmt":"2024-06-06T02:11:08","slug":"12-ways-to-use-the-value-annotation-in-spring-for-flexible-and-maintainable-applications","status":"publish","type":"post","link":"https:\/\/springmasteryhub.com\/?p=195","title":{"rendered":"12 Ways to Use the @Value Annotation in Spring for Flexible and Maintainable Applications"},"content":{"rendered":"\n<p>You may already be familiar with @Value annotation from Spring. This annotation allows you to inject some properties into your beans.<\/p>\n\n\n\n<p>But there\u2019s a lot of ways you could do that. And maybe you are not familiar with all of them.<\/p>\n\n\n\n<p>This article will show you many ways to work with @Value and some new ways you can apply to your projects.<\/p>\n\n\n\n<p>Let\u2019s explore our options!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Basic property injection<\/h3>\n\n\n\n<p>This is the most used option in Spring projects. It\u2019s the common way you can control feature flags, API keys, database connection details, etc.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;${feature.enableDarkMode}&quot;)\nprivate boolean isDarkModeEnabled;\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nfeature.enableDarkMode=true\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Hardcoded Values:<\/h3>\n\n\n\n<p>This way set the value as a constant in your code, this way you cannot change it externally.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;localhost&quot;)\nprivate String defaultServerAddress;\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. Constructor Injection<\/h3>\n\n\n\n<p>Here is to create immutable beans that need their dependencies and values upfront.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic TestBean(@Value(&quot;${mail.smtp.server}&quot;) String smtpServer) {\n    this.smtpServer = smtpServer;\n}\n\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nmail.smtp.server=smtp.example.com\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">4. SetUp Default Values:<\/h3>\n\n\n\n<p>You can provide default values when injecting your properties to avoid application crashes. If you do not have the property set, it will automatically pick the default value.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;${app.cache.ttl:60}&quot;)  \/\/ Default TTL of 60 seconds if not configured\nprivate int cacheTimeToLive;\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">5. Inject Using Set Method (Less common)<\/h3>\n\n\n\n<p>This is an option in some legacy code bases, where construction is not possible, this way of injection becomes an option.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;${log.level}&quot;)\npublic void setLogLevel(String logLevel) {\n    this.logLevel = logLevel;\n}\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nlog.level=INFO\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">6. Injecting an Array of values:<\/h3>\n\n\n\n<p>You can set an array of values, using comma-separated values, Spring will automatically split values and put them in the array positions. You can use this to set an array of allowed origins configured by properties.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;${cors.allowedOrigins}&quot;)\nprivate String&#x5B;] allowedOrigins;\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\ncors.allowedOrigins=https:\/\/example1.com,&lt;https:\/\/example2.com&gt;\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">7. Injecting a List of Values:<\/h3>\n\n\n\n<p>If you want more flexibility in your Java code, injecting a collection of values you can use SpEL to split values to create the list.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{'${notification.channels}'.split(',')}&quot;)\nprivate List&lt;String&gt; notificationChannels;\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nnotification.channels=EMAIL,SMS,PUSH\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">8. Inject Maps<\/h3>\n\n\n\n<p>You can inject in a Java map a group of configurations that uses key-value pattern.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{${http.client.config}}&quot;)\nprivate Map&lt;String, Integer&gt; httpClientConfig;\n\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nhttp.client.config={timeout: 500, maxConnections: 100}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">9. Inject a Single Value From a Map<\/h3>\n\n\n\n<p>In the same way, you can inject an entire map of values, you can use SpEL to inject a single value using its key.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{${http.client.config}&#x5B;'timeout']}&quot;)\nprivate int timeout;\n\n<\/pre><\/div>\n\n\n<p>Properties:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nhttp.client.config={timeout: 500, maxConnections: 100}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">10. Access System Properties<\/h3>\n\n\n\n<p>This method will allow you to get the system properties from the Java properties, also it gets all the properties that you set when running the application with the -D parameter.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{systemProperties&#x5B;'java.home']}&quot;)\nprivate String javaHome;\n\n<\/pre><\/div>\n\n\n<p>In this example, the <code>java.home<\/code> is already passed automatically to the process. But if you want to access some custom property you can do this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{systemProperties&#x5B;'custom.property']}&quot;)\nprivate String javaHome;\n\n<\/pre><\/div>\n\n\n<p>Running the project with custom property:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\njava -Dcustom.property=&quot;value&quot; -jar app.jar\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">11. Get Environment Variables:<\/h3>\n\n\n\n<p>You can read an environment variable from your system (if the application has access to the variable).<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{environment&#x5B;'MY_ENV_VAR']}&quot;)\nprivate String myEnvVar;\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">12. Use SpEL and Create Dynamic Properties<\/h3>\n\n\n\n<p>One common problem developers have is that the team members can be working on different OS, so you can create a dynamic property based on the system to make things more flexible.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Value(&quot;#{systemProperties&#x5B;'os.name'].toLowerCase().contains('windows') ? 'C:\\\\\\\\' : '\/'}&quot;)\nprivate String rootDirectory;\n\n<\/pre><\/div>\n\n\n<p>This will get the <a href=\"http:\/\/os.name\">os.name<\/a> from the system and decide what is the root directory to inject the value.<\/p>\n\n\n\n<p>That\u2019s it! Now you have a whole set of new ways to configure your Spring applications with @Value!<\/p>\n\n\n\n<p>That will give you more flexibility and options. It will offer a solution that fills your needs. By understanding how it works you can write more maintainable Spring applications.<\/p>\n\n\n\n<p>Test out new ways of Injecting properties into your project!<\/p>\n\n\n\n<p>If you like this topic, make sure to follow me, in the following days, I\u2019ll be explaining more about the Spring annotations!<\/p>\n\n\n\n<p>Stay tuned!<\/p>\n\n\n\n<p><a href=\"https:\/\/twitter.com\/WillianFMoya\">Willian Moya (@WillianFMoya) \/ X (twitter.com)<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www.linkedin.com\/in\/willianmoya\/\">Willian Ferreira Moya | LinkedIn<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">References<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.baeldung.com\/spring-value-annotation\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Baeldung: Spring @Value Annotation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/docs.spring.io\/spring-framework\/reference\/core\/beans\/annotation-config\/value-annotations.html\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">Spring Framework Documentation: @Value Annotations<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.digitalocean.com\/community\/tutorials\/spring-value-annotation\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">DigitalOcean: Spring @Value Annotation<\/a><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>You may already be familiar with @Value annotation from Spring. This annotation allows you to inject some properties into your beans. But there\u2019s a lot of ways you could do that. And maybe you are not familiar with all of them. This article will show you many ways to work with @Value and some new [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[6],"tags":[13,18,20,22,23,26],"class_list":["post-195","post","type-post","status-publish","format-standard","hentry","category-spring","tag-java","tag-programming","tag-software-development","tag-spring-boot","tag-spring-framework","tag-technology"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/195","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=195"}],"version-history":[{"count":0,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=\/wp\/v2\/posts\/195\/revisions"}],"wp:attachment":[{"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springmasteryhub.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}