前言:
@Value是spring的赋值注解,在这里我们来了解它的使用方式,
比如@Value("#{lx}"),
@Value("${lx}"), @Value("lx");
1.@Value("value值'')的用法
@Value("value值'')是直接把字符串(value值)直接赋值给当前字符串
2.@Value(“#{lx}”)
先解析spring表达式,将结果赋值给当前字段(解析spring表达式的结果可能是字符串或者是一个Bean对象)
3.@Value("${lx}"}
先进行占位符的替换,然后将替换后的字符串赋值给当前的字符段
根据操作系统变量,jvm环境变量,properties文件作为替换的来源
替换源
进行占位符替换
4.基于@Value做的扩展(创建注解)
4.1:@Value的源码
4.2:在properties里面添加LocalServerPort
4.3:创建LocalServerPort注解
4.4:使用@ LocalServerPort
5.源码
5.1 目录结构:
(用目录结构从下(properties)向上(LocalServerPort)开始)
依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
5.2spring.properties
lx=hello word
LocalServerPort=8080
5.3:ValueTest
package com.lx;
import com.lx.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ValueTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService1 = applicationContext.getBean("userService", UserService.class);
userService1.test();
// UserService userService=applicationContext.getBean("UserService",UserService.class);
// userService.test();
}
}
5.4:AppConfig
package com.lx;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan("com.lx")
@PropertySource("classpath:spring.properties")
public class AppConfig {
}
5.5:UserService
package com.lx.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@LocalServerPort
public String test;
// @Value("#{lx}")
// private OrderService test;
// @Value("${lx}")
// @Value("value值")
// public String test;
public void test(){
System.out.println(test);
}
}
5.6:OrderService
package com.lx.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("lx")
public class OrderService {
}
5.7:LocalServerPort
package com.lx.service;
import org.springframework.beans.factory.annotation.Value;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Value("${LocalServerPort}")
public @interface LocalServerPort {
}
版权归原作者 冲锋的禾 所有, 如有侵权,请联系我们删除。