如何对动态填充注解 [英] How-to dynamically fill a annotation

查看:138
本文介绍了如何对动态填充注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可悲的是,我忘了今天接受来自工作code和我在一起。但也许这个小例子来阐明的东西。

Sadly, I forgot to take the code from work with me today. But maybe this little example will clarify things.

我使用Hibernate映射一个bean来表。

I use hibernate to map a bean to a table.

示例:

import javax.persistence.column;
….
String columnameA;
….
@Column(name="columnameA")
public String getColumname(){
  return columnameA
}
….

我不想硬code中的COLUMNNAME在我的源代码code( columnameA 的),因为我需要切换columname无需构建整个项目。
我想用这样的:

I do not want to hardcode the columnname ("columnameA") in my sourcecode, because I need to switch the columname without building the entire project. I wanted to use something like:

@Column(name=getColumnName())

这是行不通的。的想法是,要在JNDI树的地方写COLUMNNAME,并在启动时使用它。所以我只需要重新启动才能改变COLUMNNAME应用程序。

This does not work. The idea is, to to write the columnname somewhere in the jndi tree and use it at startup. So i only need to restart the application to change the columnname.

解决这个问题的唯一途径 - 这是我能想到的 - 是我自己写的注释,它扩展了休眠类。是否有这样做的一个简单的方法?

The only way around this problem – which I can think of – is to write my own annotation, which extends the hibernate class. Is there a simpler way of doing this?

推荐答案

您不能用注解达到这个目的,但你的具体问题的解决方案是实现自定义的 NamingStrategy

You can't achieve this with annotations, but a solution to your specific problem is to implement a custom NamingStrategy:

public class NamingStrategyWrapper implements NamingStrategy {
    private NamingStrategy target;

    public NamingStrategyWrapper(NamingStrategy target) {
        this.target = target;
    }

    public String columnName(String arg0) {
        if ("columnameA".equals(arg0)) return getColumnName();
        else return target.columnName(arg0);        
    }

    ...
}

-

AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.setNamingStrategy(new NamingStrategyWrapper(cfg.getNamingStrategy()));
factory = cfg.configure().buildSessionFactory();

这篇关于如何对动态填充注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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