spring 注释_Spring @Value注释

spring 注释

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批注用于将默认值分配给变量和方法参数。 我们可以使用@Value批注读取spring环境变量以及系统变量。

Spring @Value annotation also supports SpEL. Let’s look at some of the examples of using @Value annotation.

Spring @Value注释还支持SpEL。 让我们看一些使用@Value批注的示例。

Spring @Value –默认值 (Spring @Value – Default Value)

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

我们可以使用@Value注释将默认值分配给类属性。

@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注释参数只能是字符串,但是spring尝试将其转换为指定的类型。 下面的代码可以正常工作,并将布尔值和整数值分配给该变量。

@Value("true")
private boolean defaultBoolean;

@Value("10")
private int defaultInt;

Spring @Value –Spring环境属性 (Spring @Value – Spring Environment Property)

@Value("${APP_NAME_NOT_FOUND}")
private String defaultAppName;

If the key is not found in the spring environment properties, then the property value will be ${APP_NAME_NOT_FOUND}.

如果在spring环境属性中找不到该键,则该属性值为${APP_NAME_NOT_FOUND}

We can assign a default value that will get assigned if the key is missing from spring environment properties.

我们可以分配一个默认值,如果Spring环境属性中缺少该键,则将分配一个默认值。

@Value("${APP_NAME_NOT_FOUND:Default}")
private String defaultAppName;

Spring @Value –系统环境 (Spring @Value – System Environment)

When Spring environment is populated, it reads all the system environment variables and stores it as properties. So we can assign system variables too using @Value annotation.

填充Spring环境后,它将读取所有系统环境变量并将其存储为属性。 因此,我们也可以使用@Value注释来分配系统变量。

@Value("${java.home}")
private String javaHome;
	
@Value("${HOME}")
private String homeDir;

Spring @Value – SpEL (Spring @Value – SpEL)

We can also use Spring Expression Language with @Value annotation. So we can read java home system property using SpEL too.

我们也可以使用带有@Value注释的Spring Expression Language。 因此,我们也可以使用SpEL读取java home系统属性。

@Value("#{systemProperties['java.home']}")
private String javaHome;

Spring @Value和方法 (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批注时,当所有spring配置和bean都被加载时,Spring上下文将调用它。 如果方法具有多个参数,则每个参数值都将从方法注释中映射。 如果我们想为不同的参数使用不同的值,则可以直接在参数中使用@Value批注。

@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示例 (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.

让我们创建一个简单的Spring应用程序,在其中我们将使用@Value批注读取属性并将其分配给类变量。

Create a maven project and add spring core dependencies.

创建一个Maven项目并添加spring核心依赖项。

<dependency>
	<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.

创建一个组件类,在该类中,我们将通过@Value注释注入变量值。

package com.journaldev.spring;

import org.springframework.beans.factory.annotation.Value;

public class DBConnection {

	@Value("${DB_DRIVER_CLASS}")
	private String driverClass;
	@Value("${DB_URL}")
	private String dbURL;
	@Value("${DB_USERNAME}")
	private String userName;
	@Value("${DB_PASSWORD}")
	private char[] password;

	public DBConnection() {
	}

	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.

现在,我们必须创建一个Configuration类,并为DBConnection类提供@Bean方法。

package com.journaldev.spring;

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("#{systemProperties['java.home']}")
	@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.

这是我们的主类,我们在其中创建基于注释的spring上下文。

package com.journaldev.spring;

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 1 =Test
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.

注意,在我们的上下文准备好服务用户请求之前,将调用Configuration类printValues()

That’s all for Spring @Value annotation example, you can download the example code from our GitHub Repository.

这就是Spring @Value注释示例的全部内容,您可以从我们的GitHub Repository下载示例代码。

翻译自: https://www.journaldev.com/21448/spring-value-annotation

spring 注释

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值