Spring - Create bean based on Annotation field -
update: used different approach problem.
side-question: know how spring exclude in springbootapplication
the springbootapplication:
@target(elementtype.type) @retention(retentionpolicy.runtime) @documented @inherited @springbootconfiguration @enableautoconfiguration @componentscan(excludefilters = @filter(type = filtertype.custom, classes = typeexcludefilter.class)) public @interface springbootapplication {
so when context loaded, , enableautoconfiguration executed, excludes available.
thats same want.
at bean-creation want know if annotation has field (for example boolean)
old question:
i have annotation:
@target(elementtype.type) @retention(retentionpolicy.runtime) @import(taskspringcontext.class) public @interface tasktest { class<? extends databaseservice> db() default databaseservice.class; }
this annotation used at:
@tasktest(db = databaseserviceextended.class) @springbootapplication() public class taskserver { public static void main(string[] args) { final applicationcontext ctx = springapplication.run(taskserver.class, args); } }
now, @ taskspringcontext.class want create bean based on db-field of tasktest-annotation:
@bean(name = "databaseservice") public databaseservice databaseservice() { return ?? here want return databaseserviceextended }
anyone knows how it?
i assume there's better way it, scan classpath, starting "com.example" classes annotated com.example.tasktest
, add bean definition it, bean created later.
this allow check classes annotation, of course have solve problem 2 (or more) @tasktest
on classpath.
@component public class testbeanprocessor implements beandefinitionregistrypostprocessor { @override public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) throws beansexception { ; // nothing } @override public void postprocessbeandefinitionregistry(beandefinitionregistry registry) throws beansexception { set<beandefinition> definitions = scanforbeandefinitionsin("com.example"); // base package // test if 1 or more, perhaps error, whatever beandefinition def = ...; // 1 of them class<?> clz = class.forname(def.getbeanclassname()); tasktest annotation = clz.getannotation(tasktest.class); // create new rootbeandefinition tasktext data (pretty analogous xml) rootbeandefinition datasourcedefinition = ...; registry.registerbeandefinition("datasource", datasourcedefinition); } protected set<beandefinition> scanforbeandefinitionsin(string basepackage) { classpathscanningcandidatecomponentprovider scanner = new classpathscanningcandidatecomponentprovider(false); scanner.addincludefilter(new typefilter() { @override public boolean match(metadatareader metadatareader, metadatareaderfactory metadatareaderfactory) throws ioexception { return metadatareader.getannotationmetadata().getannotationtypes().contains("com.example.tasktest"); } }); return scanner.findcandidatecomponents(basepackage); } }
Comments
Post a Comment