`
dannyhz
  • 浏览: 371240 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

spring 4 value annotation的使用

 
阅读更多
http://www.jb51.net/article/123012.htm

引用


前言
本文主要给大家介绍了关于Spring4自定义@Value功能的相关内容,使用的Spring版本4.3.10.RELEASE,下面话不多说了,来一起看看详细的介绍吧。
@Value在Spring中,功能非常强大,可以注入一个配置项,可以引用容器中的Bean(调用其方法),也可以做一些简单的运算
如下的一个简单demo,演示@Value的用法
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
?
1
2
3
app.port=9090
 
app.size=3
?
1
2
3
4
5
6
7
8
9
10
11
12
13
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的功能呢?
方法如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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));
}
}
具体使用如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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做不了
比如说,我们定义一个注解
?
1
2
3
4
5
@Retention(RUNTIME)
@Target(TYPE)
public @interface Job {
String cron();
}
这个注解需要一个cron的表达式,我们的需求是,使用方可以直接用一个cron表达式,也可以支持引用一个配置项(把值配置到配置文件中)
比如说
?
1
2
@Job(cron = "0 0 12 * * ?")
@Job(cron = "${app.job.cron}")
这种情况@Value就做不到,但是,可以用我上面的解决方案。



分享到:
评论

相关推荐

    spring aop 实现源代码--xml and annotation(带lib包)

    并定义了一个 org.springframework.aop.framework.ProxyFactoryBean对象(messageSender),FactoryBean或ApplicationContext将使用ProxyFactoryBean来建立代理对象,在这里就是messageSenderImpl建立代理对象。...

    springjdbc

    &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; &lt;!-- apache.dbcp连接池的配置 --&gt; ...

    spring-boot-reference.pdf

    4. Working with Spring Boot 5. Learning about Spring Boot Features 6. Moving to Production 7. Advanced Topics II. Getting Started 8. Introducing Spring Boot 9. System Requirements 9.1. Servlet ...

    Spring3中配置DBCP,C3P0,Proxool,Bonecp数据源

    在Spring3中配置数据源,包括DBCP,C3P0,Proxool,Bonecp主要的数据源,里面包含这些数据源的jar文件和依赖文件及配置文件。。 如Bonecp目前听说是最快的数据源,速度是传统的c3p0的25倍, bonecp.properties文件: ...

    springweb-Jackson

    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /&gt; ...

    springweb3.0MVC注解(附实例)

    &lt;display-name&gt;Spring Annotation MVC Sample &lt;!-- Spring 服务层的配置文件 --&gt; &lt;param-name&gt;contextConfigLocation &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt; &lt;!-- Spring 容器...

    Struts2+Spring3+MyBatis3完整实例

    org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,accountBiz,dataSource,sqlSessionFactory,...

    spring3.2+strut2+hibernate4

    spring3.2+strut2+hibernate4 注解方式。 spring.xml &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=...

    spring_MVC源码

    弃用了struts,用spring mvc框架做了几个项目,感觉都不错,而且使用了注解方式,可以省掉一大堆配置文件。本文主要介绍使用注解方式配置的spring mvc,之前写的spring3.0 mvc和rest小例子没有介绍到数据层的内容,...

    Spring Boot中文文档.rar

    使用@SpringBootApplication Annotation 19.运行您的应用程序 19.1.从IDE运行 19.2.作为打包应用程序运行 19.3.使用Maven插件 19.4.使用Gradle插件 19.5.热插拔 20.开发人员工具 20.1....

    spring applicationContext 配置文件

    &lt;value&gt;jxg/Qr4VbxU=&lt;/value&gt; &lt;!-- password --&gt; &lt;value&gt;jxg/Qr4VbxU=&lt;/value&gt; &lt;!-- 生产环境模式 ,才特殊处理加密密码--&gt; &lt;value&gt;true&lt;/value&gt; &lt;!-- ptc windchill的數據庫 --&gt; ...

    Spring注解 - 52注解 - 原稿笔记

    注解包含: 拦截器 , 过滤器 , 序列化 , @After , @AfterReturning , @AfterThrowing , @annotation , @Around , @Aspect , @Autowired , @Bean , @Before , @Component , @ComponentScan , @ComponentScans , @...

    springframework.5.0.12.RELEASE

    New Features ...spring-jcl routes logging inefficiently against SLF4J with log4j-to-slf4j setup [SPR-17586] #22118 Allow java.time types for setting the Last-Modified header [SPR-17571] #22103 ...

    springmybatis

    其实还有更简单的方法,而且是更好的方法,使用合理描述参数和SQL语句返回值的接口(比如IUserOperation.class),这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误.下面是详细...

    spring基础

    &lt;bean class ="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor"/&gt; &lt;!-- 移除 boss Bean 的属性注入配置的信息 --&gt; ...

    xworkdocs 对struts2学习有帮助

    是英文版本的哦,建议有耐心的读者下载. Available Pages · Documentation · Annotations · After Annotation · AnnotationWorkflowInterceptor · Before Annotation · BeforeResult ...· XWork Value Stack

    struts2.3+hibernate3.6+spring3.1整合的纯xml配置的小项目

    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;value&gt; org.whvcse.model.Userinfo ...

    yunguanjiacode06131049.zip

    import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; ...

Global site tag (gtag.js) - Google Analytics