spring 自定义让@Value被解析到

作者:wending-Y 时间:2022-12-21 13:27:49 

spring 自定义让@Value解析到

@Value 可以给字段赋值

背景

@Value通常与@PropertySource(value = “db.properties”) 组合使用读取配置注入参数,那如果我们的值是其它存储,如何才能自动赋值

实现原理

实现很简单


//自动注入此对象
@Autowired
   private Environment environment;
   @PostConstruct
   public void init() {

//拿到些对象
       MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
       PropertySourceFactory factory = BeanUtils.instantiateClass(DefaultPropertySourceFactory.class);
       //构造pathResource
       PathResource pathResource = new PathResource("/Users/xx/soft/sp.properties");
       try {
           org.springframework.core.env.PropertySource<?> sd = factory.createPropertySource("sd", new EncodedResource(pathResource));
           //设置值
           propertySources.addFirst(sd);
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

主要是通过代码得到PropertySource 这个对象,然后得到environment这个对象,设置值就可以了

Spring4自定义@Value功能

本文章使用的Spring版本4.3.10.RELEASE

@Value在Spring中,功能非常强大,可以注入一个配置项,可以引用容器中的Bean(调用其方法),也可以做一些简单的运算

如下的一个简单demo,

演示@Value的用法


import org.springframework.stereotype.Service;
/**
* 测试Bean
*/
@Service("userService")
public class UserService {

public int count() {
 return 10;
}

public int max(int size) {
 int count = count();
 return count > size ? count : size;
}
}

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppRunner implements InitializingBean {

/**
 * 引用一个配置项
 */
@Value("${app.port}")
private int port;

/**
 * 调用容器的一个bean的方法获取值
 */
@Value("#{userService.count()}")
private int userCount;

/**
 * 调用容器的一个bean的方法,且传入一个配置项的值作为参数
 */
@Value("#{userService.max(${app.size})}")
private int max;

/**
 * 简单的运算
 */
@Value("#{${app.size} <= '12345'.length() ? ${app.size} : '12345'.length()}")
private int min;

//测试
public void afterPropertiesSet() throws Exception {
 System.out.println("port : " + port);
 System.out.println("userCount : " + userCount);
 System.out.println("max : " + max);
 System.out.println("min : " + min);
}
}

app.properties

app.port=9090
app.size=3


import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan
@PropertySource("classpath:app.properties")
public class App {

public static void main( String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
    context.close();
   }
}

运行,输出结果

port : 9090
userCount : 10
max : 10
min : 3

一般的用法就是这样,用于注入一个值。

那么,能否做到,我给定一个表达式或者具体的值,它能帮忙计算出表达式的值呢? 也就是说,实现一个@Value的功能呢?

方法如下:


import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.expression.StandardBeanExpressionResolver;
public class ValueUtil {
private static final BeanExpressionResolver resolver = new StandardBeanExpressionResolver();

/**
 * 解析一个表达式,获取一个值
 * @param beanFactory
 * @param value 一个固定值或一个表达式。如果是一个固定值,则直接返回固定值,否则解析一个表达式,返回解析后的值
 * @return
 */
public static Object resolveExpression(ConfigurableBeanFactory beanFactory, String value) {
 String resolvedValue = beanFactory.resolveEmbeddedValue(value);

if (!(resolvedValue.startsWith("#{") && value.endsWith("}"))) {
  return resolvedValue;
 }

return resolver.evaluate(resolvedValue, new BeanExpressionContext(beanFactory, null));
}
}

具体使用如下:


import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

@ComponentScan
@PropertySource("classpath:app.properties")
public class App {

public static void main( String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
    //计算一个具体的值(非表达式)
    System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "1121"));
    //实现@Value的功能
    System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "${app.port}"));
    System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{userService.count()}"));
    System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{userService.max(${app.size})}"));
    System.out.println(ValueUtil.resolveExpression(context.getBeanFactory(), "#{${app.size} <= '12345'.length() ? ${app.size} : '12345'.length()}"));
    context.close();
   }
}

运行输出如下:

1121
9090
10
10
3

发现已经实现了@Value的功能

最后,可能有人就有疑问了,这有什么用呢?我直接用@Value难道不好吗?

对于大部分场景下,的确直接用@Value就可以了。但是,有些特殊的场景,@Value做不了

比如说

我们定义一个注解


@Retention(RUNTIME)
@Target(TYPE)
public @interface Job {
String cron();
}

这个注解需要一个cron的表达式,我们的需求是,使用方可以直接用一个cron表达式,也可以支持引用一个配置项(把值配置到配置文件中)

比如说


@Job(cron = "0 0 12 * * ?")
@Job(cron = "${app.job.cron}")

这种情况@Value就做不到,但是,可以用我上面的解决方案。

来源:https://blog.csdn.net/qq_22222499/article/details/114682785

标签:spring,自定义,@Value
0
投稿

猜你喜欢

  • spring cloud Ribbon用法及原理解析

    2021-11-28 15:27:21
  • 讲解.NET环境下绘制模糊数学中隶属函数分布图第1/5页

    2022-10-04 10:21:51
  • 解决MyBatis @param注解参数类型错误异常的问题

    2023-12-01 06:41:45
  • idea的spring boot项目实现更改端口号操作

    2023-11-23 03:21:17
  • 解决Android平台中应用程序OOM异常的方法

    2023-07-29 09:45:17
  • SpringBoot @Cacheable自定义KeyGenerator方式

    2022-12-25 13:23:11
  • Java中抽象类与方法的重写方式

    2023-08-25 09:20:29
  • Spring MVC学习教程之视图深入解析

    2021-12-16 23:37:55
  • C#从windows剪贴板获取并显示文本内容的方法

    2022-06-03 01:56:47
  • winform 调用摄像头扫码识别二维码的实现步骤

    2022-08-08 21:50:20
  • java开发ShardingSphere的路由引擎类型示例详解

    2023-11-29 01:18:56
  • java 的Collection接口实例详解

    2021-09-22 15:35:00
  • Ubuntu搭建Java开发环境笔记

    2023-10-10 14:27:49
  • WPF中使用CallerMemberName简化InotifyPropertyChanged的实现

    2023-05-08 16:27:07
  • 解析C#中[],List,Array,ArrayList的区别及应用

    2022-07-29 16:24:10
  • Android实现每天定时提醒功能

    2021-10-18 09:52:33
  • 浅谈EventBus

    2022-12-31 20:23:14
  • Fluent Mybatis 批量更新的使用

    2023-01-28 13:18:44
  • Android开发实现拨打电话与发送信息的方法分析

    2023-06-19 07:09:13
  • C++ vector的简单实现

    2023-04-09 17:13:02
  • asp之家 软件编程 m.aspxhome.com