google / auto

A collection of source code generators for Java.
Apache License 2.0
10.43k stars 1.2k forks source link

AutoFactory: allow annotating factories #101

Open cgrushko opened 10 years ago

cgrushko commented 10 years ago

My manually-written factories sometimes have annotations to allow some compile-time validating. Would be awesome if I could write

@AutoFactory(annotate = BlaBlaAnnotation) public Foo();

to have this generated:

@BlaBlaAnnotation class FooFactory {}

gk5885 commented 10 years ago

Since this API would only work for valueless annotations, I don't think that this is going to get much traction. The ability to add annotations to the generated types might be nice, but I'm not coming up with a decent way to specify them.

cgrushko commented 10 years ago

Perhaps this can be achieved using an interface:

class foo() {

  @AutoFactory(implements = Factory)
  public foo(...) { .. }

  @BlaBlaAnnotation(value = "2")
  interface Factory {
    ...
  }
}

All annotations appearing on the interface Factory will be copied over to the generated factory.

shevek-nebula commented 9 years ago

+1

The annotation I want is Spring's @Component - while this is zero-args (fine), but since that's an autoscanned annotation, adding it to an interface may throw up unexpected warnings in Spring.

shevek-nebula commented 9 years ago

Best effort so far is to tell AutoFactory to extend an abstract superclass with the relevant annotations, and ensure that the client of the annotations inspects the superclass.

shevek-nebula commented 9 years ago

For Spring framework, make the generated factory implement a marker interface (e.g. FactoryComponent, then add:

@ComponentScan(basePackageClasses = ApplicationBackend.class,
        includeFilters = {
    @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = FactoryComponent.class)
})
arend-von-reinersdorff commented 9 years ago

I would like to add another use case for annotating factories:

Since CDI 1.1 a CDI bean must have a scope annotation like @Dependent to be discovered. If a generated factory has no such annotation, it is not discovered as a CDI bean.

This is the new default behavior (bean-discovery-mode="annotated") since CDI 1.1. See also the specification: http://docs.jboss.org/cdi/spec/1.1/cdi-spec.html#bean_archive

For this usecase valueless annotations would work fine.

hu-chia commented 3 months ago

there is a AnnotationsToApply.