相关文章推荐
暴躁的石榴  ·  翻译 - Dolibarr ERP CRM ...·  3 月前    · 
不羁的饺子  ·  Debezium | Apache Flink·  3 月前    · 
讲道义的烈酒  ·  Debezium-JSON--流式计算 ...·  3 月前    · 
从容的大脸猫  ·  零代码第三方数据接入 | TDengine ...·  3 月前    · 
迷茫的马克杯  ·  从VBA中的范围中删除特殊字符开发者社区·  3 月前    · 
踢足球的毛豆  ·  CVPR 2023 | ...·  2 年前    · 
稳重的包子  ·  扯蛋的密码规则_laolu0837的技术博客 ...·  3 年前    · 
Code  ›  Spring @Value Annotation - A Comprehensive Guide
test string
https://www.centron.de/en/tutorial/spring-value-annotation-a-comprehensive-guide/
没读研的匕首
2 周前

MORE CENTRON

About Us
Contact
Career
Price Calculator

MORE INFOS

Datacenter
Sustainability
Blog
Business Ressources
News
  • Pricing
  • Login
  • Sign Up
  • Contact
    • Sign Up
    • Contact Sales
    • Contact
    • Content

      • 1 Spring @Value – Default Value
      • 2 Spring @Value – Spring Environment Property
      • 3 Spring @Value – System Environment
      • 4 Spring @Value – SpEL
      • 5 Spring @Value with methods
      • 6 Spring @Value Example
      Vijona
      Tutorial
      Databases
      Spring @Value Annotation – A Comprehensive Guide
      7. February 2025

      Spring @Value Annotation

      Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL. Let’s look at some of the examples of using @Value annotation.

      Spring @Value – Default Value

      We can assign default value to a class property using @Value annotation.

      @Value("Default DBConfiguration")
          private String defaultName;
          @Value annotation argument can be a string only, but spring tries to convert it to the specified type. Below code will work fine and assign the boolean and integer values to the variable.
          @Value("true")
          private boolean defaultBoolean;
          @Value("10")
          private int defaultInt;

      Spring @Value – Spring Environment Property

      Spring @Value with methods

      When the @Value annotation is found on a method, Spring context will invoke it when all the spring configurations and beans are getting loaded. If the method has multiple arguments, then every argument value is mapped from the method annotation. If we want different values for different arguments then we can use @Value annotation directly with the argument.

      @Value("Test")
          public void printValues(String s, String v){} //both 's' and 'v' values will be 'Test' 
          @Value("Test")
          public void printValues(String s, @Value("Data") String v){}
          // s=Test, v=Data

      Spring @Value Example

      Let’s create a simple Spring application where we will use @Value annotation to read properties and assign them to class variables. Create a maven project and add spring core dependencies.

      <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.6.RELEASE</version> </dependency>

      Our final project structure will look like below image, we will look each of the components one by one.

      Create a component class where we will inject variable values through @Value annotation.

      public void printDBConfigs() { System.out.println("Driver Class = " + driverClass); System.out.println("DB URL = " + dbURL); System.out.println("User Name = " + userName); // Never do below in production environment :D System.out.println("Password = " + String.valueOf(password));

      Now we have to create a Configuration class and provide a @Bean method for DBConnection class.

      import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource("classpath:db.properties") @PropertySource(value = "classpath:root.properties", ignoreResourceNotFound = true) public class DBConfiguration { @Value("Default DBConfiguration") private String defaultName; @Value("true") private boolean defaultBoolean; @Value("10") private int defaultInt; @Value("${APP_NAME_NOT_FOUND:Default}") private String defaultAppName; @Value("${java.home}") private String javaHome; @Value("${HOME}") private String homeDir; @Bean public DBConnection getDBConnection() { DBConnection dbConnection = new DBConnection(); return dbConnection; @Value("Test") public void printValues(String s, @Value("another variable") String v) { System.out.println("Input Argument 1 =" + s); System.out.println("Input Argument 2 =" + v); System.out.println("Home Directory = " + homeDir); System.out.println("Default Configuration Name = " + defaultName); System.out.println("Default App Name = " + defaultAppName); System.out.println("Java Home = " + javaHome); System.out.println("Boolean = " + defaultBoolean); System.out.println("Int = " + defaultInt);

      Here is our main class where we are creating annotation-based spring context.

      import java.sql.SQLException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringMainClass { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.scan("com.journaldev.spring"); context.refresh(); System.out.println("Refreshing the spring context"); DBConnection dbConnection = context.getBean(DBConnection.class); dbConnection.printDBConfigs(); // close the spring context context.close();

      When you will run the class, it will produce following output.

      Input Argument 2 = another variable Home Directory = /Users/pankaj Default Configuration Name = Default DBConfiguration Default App Name = Default Java Home = /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home Boolean = true Int = 10 Refreshing the spring context Driver Class = com.mysql.jdbc.Driver DB URL = jdbc:mysql://localhost:3306/Test User Name = journaldev Password = journaldev

      Notice that Configuration class printValues() is getting called before our context is ready to serve user requests. That’s all for Spring @Value annotation example, you can download the example code from our GitHub Repository – A Comprehensive Guide.

      Source: digitalocean.com

      Create a Free Account

      Register now and get access to our Cloud Services.

      Try now

      Posts you might be interested in:

      Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

      R-sub and gsub String Replacement Guide

      Databases , Tutorial
      2 hours ago
      Vijona2 hours ago How to Use sub() and gsub() in R for String Replacement R provides sub() and gsub() as core base functions for replacing text patterns. Both functions take…
      Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

      Serverless LLM Inference: Key Performance Metrics

      AI/ML , Tutorial
      3 hours ago
      Vijona3 hours ago Serverless LLM Inference Performance: Metrics That Matter in Production When teams compare serverless LLM inference models and platforms, the discussion often gets reduced to one figure: median…
      Moderne Hosting Services mit Cloud Server, Managed Server und skalierbarem Cloud Hosting für professionelle IT-Infrastrukturen

      How to Fix SSL Connect Errors

      Security , Tutorial
      22 hours ago
      VijonaYesterday at 14:17 How to Diagnose and Fix SSL Connect Errors SSL connect errors are frequent but serious issues that can stop secure communication between clients and servers. They appear…

      Do you have any questions, a specific use case, or special requirements?

      For support with large implementations, migration planning, or questions regarding a proof of concept.

      Contact Sales

      Start now for free.

      Sign up and receive a €200 credit at centron for the first 60 days.

      Start now

      This promotional offer is valid for new accounts only.

      centron logo

      centron offers flexible infrastructure and cloud services with resource-based billing to help you bring your ideas to life.

      Imprint | Privacy Policy | Terms & Conditions

      *Privacy is important to us! centron GmbH processes your personal data in accordance with the highest security standards and GDPR regulations. Your data will only be used for the specified purpose, such as providing information about our products and services. You can withdraw your consent at any time by contacting us at datenschutz@centron.de . For more details, please refer to our privacy policy .

      The offer of centron GmbH is aimed exclusively at business customers and not at end consumers. All prices are exclusive of statutory VAT.

      Products
      • ccloud3
      • Managed Server
      • Kubernetes
      • Cloud GPU
      • Managed Firewall
      • Premium Full Managing
      • Premium Managed Services
      • S3 Object Storage
      • Domain & Webhosting
      • Colocation
      • Pricing
      More centron
      • About Us
      • High Availability
      • Disaster Recovery
      • Backup
      • Trust Center
      Services & Support
      • Help Center
      • Contact
      • Tutorials
      • Blog
      • News
      • Career
     
    推荐文章
    暴躁的石榴  ·  翻译 - Dolibarr ERP CRM Wiki
    3 月前
    不羁的饺子  ·  Debezium | Apache Flink
    3 月前
    讲道义的烈酒  ·  Debezium-JSON--流式计算 Flink版-火山引擎
    3 月前
    从容的大脸猫  ·  零代码第三方数据接入 | TDengine 文档 | 涛思数据
    3 月前
    迷茫的马克杯  ·  从VBA中的范围中删除特殊字符开发者社区
    3 月前
    踢足球的毛豆  ·  CVPR 2023 | 由点到面:可泛化的流形对抗攻击,从个体对抗到流形对抗-阿里云开发者社区
    2 年前
    稳重的包子  ·  扯蛋的密码规则_laolu0837的技术博客_51CTO博客
    3 年前
    今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
    删除内容请联系邮箱 2879853325@qq.com
    Code - 代码工具平台
    © 2024 ~ 沪ICP备11025650号