首页 \ 问答 \ 春季自定义注释处理器(Custom annotation processor in spring)

春季自定义注释处理器(Custom annotation processor in spring)

我写了这个注释

    @Retention(RetentionPolicy.SOURCE)
public @interface Encrypt {

}

和它的处理器......

@SupportedAnnotationTypes("it.trecube.annotation.Encrypt")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class EncryptProcessor extends AbstractProcessor{

    public EncryptProcessor(){
        super();
    }


    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {
        String className = null;
        String packageName = null;
        String fqClassName = null;
        for (Element elem : roundEnv.getElementsAnnotatedWith(Encrypt.class)) {
            if (elem.getKind() == ElementKind.CLASS) {
                //              Encrypt encrypt = elem.getAnnotation(Encrypt.class);
                //              String message = "annotation found in " + elem.getSimpleName();
                //              processingEnv.getMessager().printMessage(Kind.NOTE, message);
                TypeElement classElement = (TypeElement) elem;
                PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

                processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.NOTE,
                        "annotated class: @Encrypt" , elem);

                className = classElement.getSimpleName().toString();
                packageName = packageElement.getQualifiedName().toString();
                fqClassName = classElement.getQualifiedName().toString();

                if (fqClassName != null) {
                    processingEnv.getMessager().printMessage(
                            Diagnostic.Kind.NOTE,
                            "fqClassName: "+fqClassName , elem);
                    Properties props = new Properties();
                    URL url = this.getClass().getClassLoader().getResource("velocity.properties");
                    try {
                        props.load(url.openStream());
                    } catch (IOException e) {
                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.ERROR,
                                "annotated class: " + classElement.getQualifiedName()+"->\n"+
                                        e.getMessage(), elem);
                        e.printStackTrace();
                        return true;
                    }
                    VelocityEngine ve = new VelocityEngine(props);
                    ve.init();

                    VelocityContext vc = new VelocityContext();

                    vc.put("className", className);
                    vc.put("packageName", packageName);


                    Template vt = ve.getTemplate("encrypt.vm");
                    File file = new File("src/main/java/"+fqClassName.replace(".", "/")+"_Encrypt.aj");
                    try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(file));

                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.NOTE,
                                "creating source file: " + file.getAbsolutePath());


                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.NOTE,
                                "applying velocity template: " + vt.getName());

                        vt.merge(vc, bw);

                        bw.close();
                    } catch (IOException e) {
                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.ERROR,
                                "applying velocity error: " + vt.getName()+"->\n"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
        return true; // no further processing of this annotation type
    }

我已经测试了所有maven客户端项目和所有工作,但当我尝试将它用于现有的春天(完整的maven构建)项目不工作...有人可以帮助我? TNX


i've written thi annotation

    @Retention(RetentionPolicy.SOURCE)
public @interface Encrypt {

}

and its processor...

@SupportedAnnotationTypes("it.trecube.annotation.Encrypt")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class EncryptProcessor extends AbstractProcessor{

    public EncryptProcessor(){
        super();
    }


    @Override
    public boolean process(Set<? extends TypeElement> annotations,
            RoundEnvironment roundEnv) {
        String className = null;
        String packageName = null;
        String fqClassName = null;
        for (Element elem : roundEnv.getElementsAnnotatedWith(Encrypt.class)) {
            if (elem.getKind() == ElementKind.CLASS) {
                //              Encrypt encrypt = elem.getAnnotation(Encrypt.class);
                //              String message = "annotation found in " + elem.getSimpleName();
                //              processingEnv.getMessager().printMessage(Kind.NOTE, message);
                TypeElement classElement = (TypeElement) elem;
                PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

                processingEnv.getMessager().printMessage(
                        Diagnostic.Kind.NOTE,
                        "annotated class: @Encrypt" , elem);

                className = classElement.getSimpleName().toString();
                packageName = packageElement.getQualifiedName().toString();
                fqClassName = classElement.getQualifiedName().toString();

                if (fqClassName != null) {
                    processingEnv.getMessager().printMessage(
                            Diagnostic.Kind.NOTE,
                            "fqClassName: "+fqClassName , elem);
                    Properties props = new Properties();
                    URL url = this.getClass().getClassLoader().getResource("velocity.properties");
                    try {
                        props.load(url.openStream());
                    } catch (IOException e) {
                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.ERROR,
                                "annotated class: " + classElement.getQualifiedName()+"->\n"+
                                        e.getMessage(), elem);
                        e.printStackTrace();
                        return true;
                    }
                    VelocityEngine ve = new VelocityEngine(props);
                    ve.init();

                    VelocityContext vc = new VelocityContext();

                    vc.put("className", className);
                    vc.put("packageName", packageName);


                    Template vt = ve.getTemplate("encrypt.vm");
                    File file = new File("src/main/java/"+fqClassName.replace(".", "/")+"_Encrypt.aj");
                    try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(file));

                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.NOTE,
                                "creating source file: " + file.getAbsolutePath());


                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.NOTE,
                                "applying velocity template: " + vt.getName());

                        vt.merge(vc, bw);

                        bw.close();
                    } catch (IOException e) {
                        processingEnv.getMessager().printMessage(
                                Diagnostic.Kind.ERROR,
                                "applying velocity error: " + vt.getName()+"->\n"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
        return true; // no further processing of this annotation type
    }

I've tested all into a maven client project and all work, but when i try to use it into an existing spring (full maven build) project not work... Can someone help me?? Tnx


原文:https://stackoverflow.com/questions/15706812
更新时间:2022-06-18 09:06

最满意答案

我会采用以下方法:

www.example.com/update/client_version

您的代码应如下所示:

import webapp2

class UpdateHandler(webapp2.RequestHandler):
    def get(self, version):
        # Do something for version

app = webapp2.WSGIApplication(
    [(r'/update/(\d+)', UpdateHandler)], 
    debug=True)

I would go with the following approach:

www.example.com/update/client_version

Your code should look like this:

import webapp2

class UpdateHandler(webapp2.RequestHandler):
    def get(self, version):
        # Do something for version

app = webapp2.WSGIApplication(
    [(r'/update/(\d+)', UpdateHandler)], 
    debug=True)

相关问答

更多
  • 不,没有。 Google App Engine (GAE)对于Python应用程序使用沙盒式Python 2.7运行时。 这是普通的App Engine托管 。 但是,在GAE您可以使用托管VM主机 。 托管VM托管可让您在可配置的Google Compute Engine虚拟机上运行GAE应用程序。 给你更多的灵活性。 在Alpha阶段, 受管理的虚拟机只支持Java 7 , Python 2.7和Go 1.4运行时环境。 要获得其他运行时(如Python 3或node.js ),您可以创建用户可配置的自 ...
  • 我将这个项目用于GAE休息应用程序: http://code.google.com/p/appengine-rest-server/ 文档很好,并且有一些例子可以了解它的工作原理。 非常容易使用。 I used this project for a GAE rest application : http://code.google.com/p/appengine-rest-server/ The documentation is good and there are some examples to und ...
  • 您可以包含其他纯python第三方软件包,您可以通过设置vendoring来实现。 供应允许您将包安装到项目的子目录中,并将它们包含在您的代码中。 - 供应第三方包 cd 在项目的根目录中创建或修改appengine_config.py以包含以下内容: from google.appengine.ext import vendor vendor.add('lib') pip install -r requirements.txt -t ...
  • 通常python文件以py结尾。 处理程序应该说 script: template-123.py 首先在本地测试您的cron作业。 您应该能够访问localhost:8000 / _ah / admin,然后单击左侧的Cron Jobs链接。 它应该列出您的所有cron作业,并且您应该能够使用页面上的链接对它们进行测试。 首先在dev_appserver上进行调试。 Usually python files end in py. the handler should say script: templat ...
  • 正如这里所写,这是谷歌appengine公共问题跟踪器上的跟踪问题。 所以每个人都可以去那里检查更新。 同时我解决了从app.yaml删除login: admin的问题,在我的服务处理程序中,我已经手动检查了标头X-Appengine-Inbound-Appid及其值的存在。 As written here this is a tracked issue now on google appengine public issue tracker. So everyone can go there to che ...
  • 我会采用以下方法: www.example.com/update/client_version 您的代码应如下所示: import webapp2 class UpdateHandler(webapp2.RequestHandler): def get(self, version): # Do something for version app = webapp2.WSGIApplication( [(r'/update/(\d+)', UpdateHandler)], ...
  • 您可以使用香草DjangGAE来完成您提到的所有事情。 一个很好的起点 值得一提的是,有一些值得注意的局限性。 这些也列在我链接的网站上。 You can use vanilla DjangGAE to do everything you'd mentioned. A good starting point It's worth mentioning that there are a few notable limitations. Those are also listed in the site I'd ...
  • 混乱的奇怪事情发生在这里。 首先, app.yaml我必须在root设置之前放置我的/cron处理程序: handlers: - url: /cron script: assets/backup/main.py - url: / static_files: assets/index.html upload: assets/index.html 否则我会因为无法找到该文件而感到疯狂。 这一点实际上是有道理的。 接下来是Python代码。 不确定这里发生了什么,但最终我设法通过这样做: #!/u ...
  • 根据文档, Alloc字段显示已分配且仍在使用的字节。 但是,在垃圾收集语言中,当GC释放内存时,它不会立即返回系统(可以很快再次请求,所以为什么还要将它返回?)。 所以你真正需要监视的是Sys字段,它计算从系统获得的字节数。 您可能对本文感兴趣,并提供了一些如何最大限度地减少内存使用量的见解。 According to the docs Alloc field shows bytes allocated and still in use. In garbage-collected language, ho ...
  • 在main.py文件(即main模块)中, application是main()函数内的变量,而不是main模块的属性。 基本上你不需要main()函数。 GAE对使用Django有一些特定的支持,我强烈建议浏览Django支持文档和Django App示例 。 In your main.py file (i.e. the main module) application is a variable inside the main() function, not an attribute of the ma ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)