Custom annotation like @Value

后端 未结 3 965
时光说笑
时光说笑 2021-01-13 05:50

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 data

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 06:50

    Approach #1:

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

    Your aspect will then:

    • Read the property value in the annotation
    • Look up the required value an inject it into the class.

    AOP Kickstart

    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

    Approach #2:

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

    • It will look at your bean definitions, and fetch the underlying class.
    • It will then check for the annotation in the class, using reflection.
    • It will update the bean definition to include injecting the property as per the value in the annotation.

    . . 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?

    Namespace Handler

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

    
    

    as an alternative to:

    
                                                            
提交回复
热议问题