自定义注释,例如@Value [英] Custom annotation like @Value

查看:112
本文介绍了自定义注释,例如@Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一种添加自定义注释的方法,例如

I need to create a means to add a custom annotation like

@Value("${my.property}")

但是,就我而言,我需要从数据库而不是属性文件中获取值.

However, in my case I need to get the value from a database rather then a properties file.

基本上,我想在容器启动时创建一个bean,该bean从数据库中读取属性名称值对,然后可以将它们注入属于其他bean的字段中.

Basically I would like to create a bean on container startup that reads in property name value pairs from a database and can then inject these into fields belonging to other beans.

推荐答案

方法1:

一种方法是使用切入点表达式与具有此批注的任何方法匹配的方式创建一个Aspect.

One way is to create an Aspect, with a point-cut expression that matches any method having this annotation.

您的方面将随后:

  • 读取注释中的属性值
  • 查找所需的值,然后将其注入到类中.

AOP Kickstart

AOP Kickstart

这是在春季开始使用AOP的指南

Here's a guide to getting started with AOP in Spring

http://www.tutorialspoint.com/spring/aop_with_spring.htm

联接点匹配

Joinpoint matching

以下是描述如何创建与注释匹配的连接点的参考:

Here's a reference that describes how to create a join-point that matches on annotations: http://eclipse.org/aspectj/doc/next/adk15notebook/annotations-pointcuts-and-advice.html

方法2:

另一种方法是使用

Another way is to use a BeanFactoryPostProcessor - this is essentially how a PropertyPlaceholderConfigurer works.

  • 它将查看您的bean定义,并获取基础类.
  • 然后它将使用反射检查类中的注释.
  • 它将更新bean定义,以包括根据注释中的值注入属性.

. .实际上,我认为方法2听起来更像您想要的-所有处理都在启动"时进行. . . (实际上,您甚至在启动之前就修改了bean配方). .而如果您使用AOP,那么您将拦截方法调用,这对您来说可能为时已晚?

. . actually I think approach #2 sounds more like what you want - all of the processing happens on "start-up". . . (In actual fact your modifying the bean recipes even before startup). . whereas if you used AOP, you'd be intercepting method invocations, which might be too late for you?

命名空间处理程序

如果您愿意,甚至可以创建自己的Spring 命名空间处理程序 ,以简洁的方式打开后处理程序.例如:

If you wanted you could even create your own Spring namespace handler to turn on your post processor in a terse way. Eg:

<myApp:injectFromDb />

替代:

<bean class="MyDatabaseLookupProcessorImpl etc, etc. />

更新:方法3

从Spring 3.1开始,还有 PropertySourcesPlaceholderConfigurer ,它将为您提供大部分管道,因此您可以用更少的代码来实现.

As of Spring 3.1 there's also the PropertySourcesPlaceholderConfigurer, that will provide most of the plumbing for you, so you can achieve this with less code.

这篇关于自定义注释,例如@Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆