本篇文章為大家展示了在Spring4中怎么對@Value進行自定義,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
@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}")
上述內容就是在Spring4中怎么對@Value進行自定義,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。